我有RewriteRule
可以使用。
RewriteBase /my/path/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /my/path/index.php [L]
所以带有斜杠的URL工作。 http://localhost/my/path/foo/bar/
问题是没有尾部斜杠的URL会破坏相对链接。再加上看起来不太好。
这达到内部重定向的最大数量。
RewriteRule ^/my/path/(.*[^/])$ $1/ [R]
RewriteRule . /my/path/index.php [L]
这样做...... http://localhost/my/path/index.php/bar/
RewriteRule . /my/path/index.php
RewriteRule ^/my/path/(.*[^/])$ $1/ [R,L]
任何想法或解决方案?
答案 0 :(得分:2)
mod_rewrite
的令人困惑的功能是,在内部重定向之后,即使是一个符合[L]
的人,也会再次处理整套规则强>从一开始。
因此,您将不存在的路径重定向到index.php
,但是然后添加斜杠的规则将导致您无法获得所需的结果。
在您的情况下,您只需要将文件不存在条件放在两个重定向规则上:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /my/path/index.php [L]
或者可能将此条件移至文件顶部:
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L] # redirect to same location to stop processing
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R]
RewriteRule ^ /my/path/index.php [L]
还有一个未记录的技巧可以在内部重定向后停止处理,这可以使更复杂的规则集更容易编写 - 使用REDIRECT_STATUS
环境变量,该变量在内部重定向后设置:
RewriteCond %{ENV:REDIRECT_STATUS} . # <-- that's a dot there
RewriteRule ^ - [L] # redirect to same location to stop processing
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R]
RewriteRule ^ /my/path/index.php [L]