regex - 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”。
到底是怎么回事?为什么我的正则表达式中的点会以这种方式与我的捕获组的内容混淆?
解决方案
问题是您的规则正在循环,因此运行了两次。在第一次执行之后,在第二次执行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]
推荐阅读
- sql - JDBC 连接不支持带引号的标识符(dbWriteTable 错误)
- react-native - 如何使用 expo 图像选择器从图库中获取全尺寸照片
- ansible - 基于主机名(嵌套变量名)自动化部署环境 Ansible
- docker - 软件包不会安装在 docker 中
- ruby - 使用“remember_host!”是否存在安全风险?使用 net-ssh ruby gem 获取 HostKeyMismatch 异常时?
- git - 无法推送到自己的存储库:权限被拒绝(公钥)
- mysql - 标题栏不应包含单引号标点
- android - 离子谷歌登录在 android 上工作但在 IOS 上工作:有效负载观众!= requiredAudience
- c# - 如何从用户那里获得多项选择的正确价值?
- html - 我可以在 WordPress 中使用现有的 HTML 和 CSS 代码吗?