三个独立的场景:
- 在www根目录中有一个文件
foo.html
,没有文件夹foo
:/foo.hmtl
- 在www根目录中有一个文件夹
foo
,文件index.html
位于该文件夹中:/foo/index.html
- 在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.html
到example.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/foo
或example.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]