1

I'm hosting a website that's just a bunch of static .html files. I don't want to have the .html file extension in the URLs, so I've added a rewrite rule:

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME}\.html -f
  RewriteRule ^(.+)$ /$1.html [L]

This is simple enough and works fine, but I would now also like to redirect (302) URLs ending in .html to the canonical path, i.e. without the file extension. I've tried the following:

  RewriteCond %{REQUEST_FILENAME} \.html$
  RewriteRule ^(.+)\.html$ /$1 [L,R]

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME}\.html -f
  RewriteRule ^(.+)$ /$1.html [L]

However, that leads to an endless redirect loop. I suspect that's because the second rule, the internal rewrite, is still triggering the first rule, the external redirect.

How else can I achieve this? I've looked through all the rewrite flags and tried a bunch that sounded promising, but I haven't managed to make this work. How can I both rewrite from foo.html to foo and still do an internal rewrite from foo to foo.html?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
futlib
  • 8,258
  • 13
  • 40
  • 55

1 Answers1

2

There are several questions asking about how this procedure works. Use THE_REQUEST variable:

RewriteCond %{THE_REQUEST} ^GET\ /(.+)\.html
RewriteRule \.html$ /%1 [R=302]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ /$1.html [L]
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • Ouch, makes me doubt my Google-Fu :( Works brilliant. – futlib Nov 29 '15 at 08:42
  • This is very useful. How would one extend it so that the following works too? /foo => /foo/, /foo.html => /foo/ and /foo/ is as is and all three return foo.html. Thank you. – Vishal Aug 25 '16 at 04:21