How to hide the .html extension with Apache mod_rewrite
Try this rule:
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [L]
This will rewrite all requests that can be mapped to an existing file when appending a .html
.
The previous answers don't check if the requested path is a directory.
Here is the full rewrite condition which doesn't rewrite, if requested path is a directory (as stated by the original question):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d # is not directory
RewriteCond %{REQUEST_FILENAME}\.html -f # is an existing html file
RewriteRule ^(.*)$ $1.html # rewrite index to index.html
To be SEO friendly and avoid double content, redirect the .html
URLs:
# Redirects example.com/file.html to example.com/file
RewriteCond %{REQUEST_FILENAME} !-d # is not directory
RewriteCond %{REQUEST_FILENAME}\.html -f # is an existing html file
RewriteCond %{REQUEST_URI} ^(.+)\.html$ # request URI ends with .html
RewriteRule (.*)\.html$ /$1 [R=301,L] # redirect from index.html to index
If you need the same for scripts take a look here: How can I use .htaccess to hide .php URL extensions?