【问题标题】:.htaccess - preventing infinite loops with URL rewriting.htaccess - 通过 URL 重写防止无限循环
【发布时间】:2015-06-14 14:23:00
【问题描述】:

我有一个 .htaccess,其中包含以下内容:

<Files .htaccess>
order allow,deny
deny from all
</Files>

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^(.*)/maintenance/(.*)$ [NC]

RewriteRule ^(.*).jpg$ /mysite/maintenance/transparent.png [NC,R=302,L]
RewriteRule ^(.*).jpeg$ /mysite/maintenance/transparent.png [NC,R=302,L]
RewriteRule ^(.*).gif$ /mysite/maintenance/transparent.png [NC,R=302,L]
RewriteRule ^(.*).png$ /mysite/maintenance/transparent.png [NC,R=302,L]

RewriteRule ^(.*).php$ /mysite/maintenance/maintenance.php [NC,R=302,L]

在本地主机上测试。

使用这些设置,我在尝试加载 http://localhost/mysite/test.php 时出现无限循环,(正确)重定向到 http://localhost/mysite/maintenance/maintenance.php

循环似乎是由于 4 图像重定向(注意:维护页面有一个位于维护文件夹根目录中的唯一 jpg 背景图像)。注释这 4 条重定向行可以解决问题。

但我不明白为什么我进入无限循环,因为 /maintenance/ 路径本身被排除在 RewriteCond 的重定向之外,以及为什么图像上的重定向会干扰这个问题。

你能帮忙吗?

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-rewriting infinite-loop


    【解决方案1】:

    您必须像这样重新排序您的RewriteConds

    RewriteEngine On
    
    RewriteRule \.jpg$ /mysite/maintenance/transparent.png [NC,R=302,L]
    RewriteRule \.jpeg$ /mysite/maintenance/transparent.png [NC,R=302,L]
    RewriteRule \.gif$ /mysite/maintenance/transparent.png [NC,R=302,L]
    RewriteCond %{REQUEST_URI} !^.*/maintenance/.*$ [NC]
    RewriteRule \.png$ /mysite/maintenance/transparent.png [NC,R=302,L]
    
    RewriteCond %{REQUEST_URI} !^.*/maintenance/.*$ [NC]
    RewriteRule \.php$ /mysite/maintenance/maintenance.php [NC,R=302,L]
    

    RewriteCond 指令只影响它之后的第一个 RewriteRule

    【讨论】:

    • 有没有办法将重写规则分组到一个唯一(或分组)的 rewritecond 下?
    • 很遗憾,没有……是mod_rewritebehaviour
    【解决方案2】:

    我知道这个答案已被接受,但这里可以使用更短的方法:

    RewriteEngine On
    
    RewriteRule \.(jpe?g|gif)$ /mysite/maintenance/transparent.png [NC,R=302,L]
    
    RewriteCond %{REQUEST_URI} !/maintenance/ [NC]
    RewriteRule \.(png|php)$ /mysite/maintenance/transparent.$1 [NC,R=302,L]
    

    【讨论】:

      猜你喜欢
      • 2011-03-08
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 2014-01-09
      • 2013-11-23
      • 1970-01-01
      • 2013-01-25
      • 2012-05-08
      相关资源
      最近更新 更多