没有.html文件扩展名的URL+相应的重定向+没有尾部斜杠



三个独立的场景:

  1. www根目录中有一个文件foo.html,没有文件夹foo:/foo.hmtl
  2. www根目录中有一个文件夹foo,文件index.html位于该文件夹中:/foo/index.html
  3. www根目录中有一个文件夹foo,文件bar.html位于该文件夹中:/foo/bar.html

所有三种情况下的目标都是:

规范url应为example.org/foo:

  • example.org/foo.html应重定向到example.org/foo
  • example.org/foo/应重定向到example.org/foo
  • example.org/foo//应重定向到example.org/foo
  • example.org/foo/index.html应重定向到example.org/foo
  • example.org/foo/bar.html应重定向到example.org/foo

我对场景#1的第一种方法:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule foo foo.html [NC,L]

请求example.org/foo返回/foo.html的内容,但是当然不存在从example.org/foo.htmlexample.org/foo的重定向。

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule foo foo.html [NC,L]
Redirect 301 foo.html foo

请求example.org/fooexample.org/foo.html返回HTTP状态代码500内部服务器错误

我对场景#1的第二种方法:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule foo foo.html [R=301,NC,L]

请求example.org/foo重定向到example.org/foo.html,然后返回/foo.html的内容。

我试了很多,但都没有得到我想要的结果。那么,有人能帮我解释一下吗?就像我三岁的时候一样?;-(

请您尝试以下操作。

RewriteEngine On
### from example.org/foo/ OR example.org/foo// ----> example.org/foo ####
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/(foo)/+?$
RewriteRule ^.*$ /%1 [NC,R=302,L]
### redirect foo.html to foo with showing foo.html content ####
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_URI} ^/(foo).html$ [NC]
RewriteRule ^.*$ /%1 [NC,R=302,L]

###redirect from foo/index.html to foo AND foo/bar.html to foo ####
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_URI} ^/(foo)/(index|bar).html [NC]
RewriteRule ^.*$ /%1 [NC,R=302,L]

最新更新