【问题标题】:Why would mod_rewrite rewrite twice?为什么 mod_rewrite 会重写两次?
【发布时间】:2009-02-01 01:17:52
【问题描述】:

I only recently found out about URL rewriting,所以我还有很多东西要学。

虽然遵循 Easy Mod Rewrite 教程,但其中一个示例的结果确实让我感到困惑。

RewriteBase /
RewriteRule (.*) index.php?page=$1 [QSA,L]

/home 重写为 /index.php?page=index.php&page=home

我认为重复可能是由我的主机配置中的某些内容引起的,但全新安装 XAMPP 也是如此。

那么,有谁知道为什么这似乎解析了两次?

而且,在我看来,如果要这样做,那将是一个无限循环——为什么它会在 2 个循环时停止?

【问题讨论】:

    标签: apache mod-rewrite url-rewriting


    【解决方案1】:

    来自this page 上的示例 1,这是您问题中链接的教程的一部分:

    假设您使用的 CMS 系统将对所有内容的请求重写为单个 index.php 脚本。

    RewriteRule ^(.*)$ index.php?PAGE=$1 [L,QSA]
    

    但每次运行时,无论您请求哪个文件,PAGE 变量始终包含“index.php”。

    为什么?您最终将进行两次重写。首先,您请求 test.php。这将被重写为 index.php?PAGE=test.php。现在对 index.php?PAGE=test.php 发出第二个请求。这仍然与您的重写模式匹配,然后又被重写为 index.php?PAGE=index.php

    一种解决方案是添加一个 RewriteCond 来检查文件是否已经是“index.php”。还允许您将图像和 CSS 文件保存在同一目录中的更好解决方案是使用 RewriteCond 来检查文件是否存在,使用 -f。


    1链接指向 Internet 档案,因为教程网站似乎离线

    【讨论】:

      【解决方案2】:

      来自Apache Module mod_rewrite documentation

      'last|L'(最后一条规则)
      […] 如果 RewriteRule 生成内部重定向 […] 这将重新注入请求,并导致从第一个 RewriteRule 开始重复处理。

      为防止这种情况,您可以使用额外的 RewriteCond 指令:

      RewriteCond %{REQUEST_URI} !^/index\.php$
      RewriteRule (.*) index.php?page=$1 [QSA,L]
      

      或者您将模式更改为不匹配 index.php 并使用 REQUEST_URI 变量,无论是在重定向中还是稍后在 PHP ($_SERVER['REQUEST_URI']) 中。

      RewriteRule !^index\.php$ index.php?page=%{REQUEST_URI} [QSA,L]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-18
        • 1970-01-01
        • 2017-01-08
        • 1970-01-01
        相关资源
        最近更新 更多