问题
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
?
回答1:
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]
来源:https://stackoverflow.com/questions/33977592/apache-how-can-i-both-redirect-foo-html-to-foo-and-rewrite-foo-to-foo-html