首页 > 解决方案 > mod_rewrite 在 . 正则表达式中的(点)

问题描述

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

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”。

到底是怎么回事?为什么我的正则表达式中的点会以这种方式与我的捕获组的内容混淆?

标签: regexmod-rewriteapache2

解决方案


问题是您的规则正在循环,因此运行了两次。在第一次执行之后,在第二次执行REQUEST_URItarget.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]

推荐阅读