URL 重写包括尾部斜杠(如果不存在)

2024-02-22

我有这个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]

有什么想法或解决方案吗?


令人困惑的特点是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]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

URL 重写包括尾部斜杠(如果不存在) 的相关文章

随机推荐