【问题标题】:mod_rewrite behaving strangely when . (dot) in regexmod_rewrite 在 .正则表达式中的(点)
【发布时间】:2019-11-21 22:17:28
【问题描述】:

我正在尝试将所有到我网站的流量重定向到单个脚本,如下所示:

example.com/fictitious/path/to/resource

应该变成

example.com/target.php?path=fictitious/path/to/resource

我已经按如下方式设置了我的 .htaccess 文件:

RewriteEngine on
RewriteBase "/"
RewriteRule "^(.*)$" "target.php?path=$1"

target.php 看起来像这样用于测试目的:

<?php echo $_GET["path"] ?>

但是,当我转到“example.com/path/to/resource”时,target.php 只会回显“target.php”而不是“path/to/resource”。当我更改我的 .htaccess 时

[...]
RewriteRule "^([a-zA-Z\/]*)$" "target.php?path=$1"

果然,target.php 忠实地呼应了“path/to/resource”,但只要我在我的规则中添加一个 ESCAPED 点:

[...]
RewriteRule "^([a-zA-Z\/\.]*)$" "target.php?path=$1"

target.php 再次回显“target.php”。

发生了什么事?为什么我的正则表达式中的点会以这种方式与我的捕获组的内容混淆?

【问题讨论】:

    标签: regex mod-rewrite apache2


    【解决方案1】:

    问题是您的规则正在循环,因此运行了两次。在第一次执行后REQUEST_URI 变为target.php,在第二次执行中,您在path 参数中得到相同的结果。

    这是因为您没有任何条件避免对现有文件和目录运行此规则。

    你可以使用:

    RewriteEngine on
    
    # If the request is not for a valid directory
    RewriteCond %{REQUEST_FILENAME} !-d
    # If the request is not for a valid file
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ target.php?path=$1 [L,QSA]
    

    【讨论】:

    • 谢谢!所以我是否正确地假设它从用户请求中获取 URL,重写它,然后从顶部开始重写 URL 的链,直到 URL 不再改变?因为我之前的假设是,它只是遍历链一次,只重写请求 URL。
    • 是的,您的假设是正确的,它再次从顶部开始。有关详细信息,请参阅此:httpd.apache.org/docs/current/rewrite/tech.html
    猜你喜欢
    • 1970-01-01
    • 2019-09-04
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多