我的 htdocs/MVC/文件夹中有一个 .htaccess 文件,如下所示
RewriteEngine On
# if its already been rewritten to the specific folder
RewriteCond %{REQUEST_URI} ^/MVC/public/img/(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^/MVC/public/index.php$
# skip next two rules
RewriteRule .? - [S=2]
# rewrite image requests
RewriteRule (.*\.(jpg|png|gif))$ public/img/$1 [L]
# rewrite all other requests to the front controller index.php
RewriteRule (.*) public/index.php?url=$1 [QSA,L]
我想要实现的是所有图像请求都发送到文件夹 MVC/public/img,所有其他请求都发送到文件夹 MVC/public 中的前端 Controller index.php。这是设置这些规则并防止 mod_rewrite 循环的最佳方法吗?
最佳答案
使用 S
标志跳过可以,但缺点是:
- 阅读起来有点困难(如果其他人正在看的话)
- 如果需要附加新规则,则需要检查其跳过的方式
- 如果您的规则变得越来越复杂,保持正确的跳过就会变得越来越困难
防止循环的其他可能方法:
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]
如果在上一个循环中应用了规则(或应用了 mod_alias 重定向),将其放在规则的最顶部将立即完全停止重写。
所以它看起来像这样:
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]
# rewrite image requests
RewriteRule (.*\.(jpg|png|gif))$ public/img/$1 [L]
# rewrite all other requests to the front controller index.php
RewriteRule (.*) public/index.php?url=$1 [QSA,L]
优点:你永远不必担心循环,因为第二次会立即以 ENV 检查结束 缺点:如果您碰巧需要创建循环规则,此方法将阻止其工作
关于regex - htaccess 中的 mod_rewrite : best way to prevent looping?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13008782/