regex - htaccess 中的 mod_rewrite : best way to prevent looping?

标签 regex apache mod-rewrite

我的 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 标志跳过可以,但缺点是:

  1. 阅读起来有点困难(如果其他人正在看的话)
  2. 如果需要附加新规则,则需要检查其跳过的方式
  3. 如果您的规则变得越来越复杂,保持正确的跳过就会变得越来越困难

防止循环的其他可能方法:

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/

相关文章:

regex - 有效电子邮件地址的正则表达式?

php - 使用 RewriteRule 发送 POST 数据

php - 自定义错误 403 页面 PHP

.htaccess - htaccess seo 友好的 URL

wordpress - 如何用 %23 重写 URL?

regex - 使用 sed 和/或 awk,如何对文件中的所有文本进行 sed 交换,直到我看到与正则表达式匹配的行?

MySQL:匹配这些条件的正则表达式?

javascript - 使用正则表达式匹配括号之间的内容(仅此而已)

apache - 在 apache 中找不到虚拟主机的 WAMP 服务器名称

apache - 为 JIRA ServiceDesk 重写条件规则