How to use htaccess to remove html file extension from urls - mod-rewite guide

htaccess rule to remove .html extension from URLs

A 100% working and tested rule to trim .html from URLs . You can just copy and paste it to your .htaccess or server.config files on Apache server.

RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^.+$ /%1 [R=301,L]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^/?(.+)/?$ /$1.html [L]
The RewiteRule above will convert your URL
http://example.com/file.html
To
http://example.com/file
If you want to add a traling slash to your new non-html URL forexample example.com/file/ then just put a traling slash at the end of the destination path of the first rule .
Change the first RewriteRule line to
RewriteRule ^.+$ /%1/ [R=301,L]
This will automatically force a traling slash on your html URLs and your URL example.com/fileName.html will get redirected to example.com/fileName/ .

Where to put the RewriteRule

You can use it either in your .htaccess or server.config file. In case you don't have access to the main server.config file on your server then it's ok to use it in htaccess file.
You can use the rule in your public_html/.htaccess so that it can apply to all folders and subfolders.

If you don't want the rule to apply to a specific sub directory then create a seprate .htaccess file with the following single line contents RewriteEngine on and save the file. Then your public_html/.htaccess will not affect the subdirectory.

Also see this : How to remove .php extension from URLs .

Post a Comment

0 Comments