php - 为什么 $_GET = index.php

标签 php regex .htaccess mod-rewrite

在我的 .htaccess 文件中我有:

RewriteEngine On
RewriteBase /
RewriteRule ^([^/]+)/?$ index.php?ToDo=$1 [L,QSA]

当执行 print_r($_GET) 时,它输出

Array ( [ToDo] => index.php ) 

但是,当我将重写规则更改为

^([^/.]+)/?$ index.php?ToDo=$1 [L,QSA] 

print_r 然后输出 $_GET 是一个空数组。有人可以向我解释为什么会这样吗?

最佳答案

让我们举个例子 URI /abc:

你的第一个正则表达式:

^([^/]+)/?$

匹配/abc并将其重写为:

/index.php?ToDo=abc

现在 mod_rewrite 引擎再次运行并匹配正则表达式 ^([^/]+)/?$ 再次为 URI /index.php 并将其重写为:

/index.php?ToDo=index.php

你的第二个正则表达式:

^([^/.]+)/?$

工作正常,因为它不匹配 /index.php URI。

最好的写法是这样的:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?ToDo=$1 [L,QSA]

如果请求是针对有效文件或目录,这两行 RewriteCond 将阻止重写。

关于php - 为什么 $_GET = index.php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24811240/

相关文章:

php - 使用 .htaccess 文件和 PHP 创建自定义 URL

.htaccess - 防止静态 Assets 的 cookieless 子域被搜索引擎索引

php - 确保电子邮件和用户名都没有被占用

php - PayPal 付款 - HTTP 响应代码 400

php - 教义悲观锁

ruby - 正则表达式匹配类中除某些字符外的所有字符

PHP 扩展无法在 Web 目录中运行,而 .html 扩展可以运行

php - 周数和周日

regex - 在 Swift 3 中搜索正则表达式

regex - 当模式具有相似文本时,如何使用 RegEx 在 Python 中获取所有匹配项?