【问题标题】:htaccess: RewriteCond matched what is in tester unmatchedhtaccess:RewriteCond 匹配测试仪中的内容不匹配
【发布时间】:2014-10-05 07:03:26
【问题描述】:

我还有一个关于 mod_rewrite 的问题。如果用户想要图像(uri 末尾的.png、.jpe?g、.gif)然后重定向到 index1.html,否则重定向到 index2.html。测试人员 (http://htaccess.madewithlove.be/) 与没有 .png,jpe?g,.gif 的 uri 不匹配,因为在正确的范围内,但我的 localhost 匹配,这就是问题所在。

正确的例子: 输入:

localhost/image.png

输出

localhost/index1.html

输入:

localhost/image

输出

localhost/index2.html

但我的本地主机真正做了什么: 输入:

localhost/image.png

输出

localhost/index2.html

输入:

localhost/image

输出

localhost/index2.html

我的 htaccess:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !^(.*)(.png|.jpe?g|.gif)$
RewriteRule ^(.*)$ index2.html

RewriteCond %{REQUEST_URI} ^(.*)(.png|.jpe?g|.gif)$
RewriteRule ^(.*)$ index1.html

你能帮忙吗?谢谢。

【问题讨论】:

    标签: php regex apache .htaccess mod-rewrite


    【解决方案1】:
    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{REQUEST_URI} (?!.*?\.png|.*?\.jpe?g|.*?\.gif)^(.*?)$
    RewriteRule ^(.*)$ index2.html
    
    RewriteCond %{REQUEST_URI} (?=.*?\.png|.*?\.jpe?g|.*?\.gif)^(.*?)(.png|.jpe?g|.gif)$
    RewriteRule ^(.*)$ index1.html
    

    试试这个。为 .png 添加了一个lookahead.Postive,对于没有 .png 的为否定。

    【讨论】:

    • 谢谢。但同样的情况 - 在测试仪中有效,但在 localhost 中无效。始终重定向到 index2.html。 :(
    【解决方案2】:

    这样吧:

    RewriteEngine On
    RewriteBase /
    
    RewriteRule \.(png|jpe?g|gif)$ index1.html [L,NC,R]
    
    RewriteRule !^(index[12]\.html|[^.]+\.(png|jpe?g|gif))$ index2.html [L,NC,R]
    

    【讨论】:

      【解决方案3】:

      你在荒谬地滥用RewriteCond。将其简化为:

      RewriteEngine On
      RewriteBase /
      RewriteRule (\.png|\.jpe?g|\.gif)$ index2.html [L,R=303]
      RewriteRule !^index[12]\.html$ index1.html [L,R=303]
      

      [L] 修饰符(“最后一个”)确保不再处理任何规则,从而无需检查第二条规则。 [R=303] 使其成为 303(请参阅其他)重定向 - 如果需要,请更改 HTTP 状态代码。

      【讨论】:

      • 谢谢。再次不在本地主机上工作,仍然重定向到 index1.html。也许我的本地主机有问题?
      • 好的,我将在另一个主机上测试它。
      • 刚刚意识到您可能正在经历递归(在浏览器中打开网络选项卡进行监控!)。对其进行了编辑以防止这种情况发生。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      相关资源
      最近更新 更多