Apache: How can I both redirect foo.html to foo and rewrite foo to foo.html?

本小妞迷上赌 提交于 2019-12-11 12:11:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!