How to get Apache 2.2 to use foo.html in preference to foo/ when both exist?

I'm moving a site from dynamic php to static html, while retaining the domain name. I've created a temporary mirror using httrack. The mirror site works well, except that pages which used to be foo/about are now foo/about.html. When I replace the live site with the mirror all incoming links and bookmarks will be broken, something I want to avoid.

I've discovered using Options +MultiViews in my .htaccess file achieves most of the above, except when file and directory names collide: if the url is http://example.org/how_to apache tries to load how_to/index.* instead of how_to.html when the latter exists.

I've tried a few mod_rewrite rule sets but only succeeded in duplicating the multiviews behaviour at the expense of a more complicated .htaccess file:

# Add .html internally (but remove externally):
RewriteEngine   on
RewriteBase   /

# Skip the next 2 rules (the .html stripping redirections)
# if the current URL doesn't end with .html
# or the requested file doesn't exist:
RewriteCond %{THE_REQUEST} !\.html\    [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .? - [S=2]

# Redirect /dir/index.html to /dir/:
RewriteRule ^(.*/|)index\.html$   $1 [R=301,L]
# Redirect /dir/file.html to /dir/file:
RewriteRule ^(.+)\.html$   $1 [R=301,L]

# Internally, treat request for /dir/file as /dir/file.html
# (but only if /dir/file.html exists):
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html   [L] 

As you've likely surmised by now. I'm on a shared host and can only use .htaccess directives. This is static html, php, cgi, etc. are not available.

Hat tip to cjm and pne on the nearlyfreespeech.net forum who got me this far.

  • I note there are two close votes in less than 30 minutes. Anyone care to explain what's wrong or unwelcome about the question? Txs. Commented Jan 22, 2012 at 8:10
  • @ziesemer, thanks. I didn't know about webmasters.SE. I asked here because there are >8k htaccess questions present, vs <1K at ServerFault.com. I guess the network is big enough now there needs to be a "where do I ask my question?" question... Should I wait for a mod to move this to webmasters or just delete and repost there myself? Commented Jan 22, 2012 at 8:22

1 Answer 1


mod_dir appears to be thwarting your efforts. Give this a try instead:

DirectorySlash off

RewriteEngine on

RewriteCond %{REQUEST_FILENAME}\.html   -f
RewriteRule .* %{REQUEST_FILENAME}.html [L,QSA]
  • thank you! so very much. I've spent hours and hours trying to figure out the right parameters and syntax. To have it boiled down to just 4 lines and just work is sweet indeed. Commented Jan 24, 2012 at 5:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.