【问题标题】:Why does $_GET = index.php为什么 $_GET = index.php
【发布时间】:2014-09-08 18:42:12
【问题描述】:

在我的 .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 是一个空数组。有人可以向我解释为什么会发生这种情况吗?

【问题讨论】:

  • 产生此输出的 URL 是什么?
  • 完整的 url 在我的本地服务器上并输出 //local.test/

标签: php regex .htaccess mod-rewrite


【解决方案1】:

我们举个例子 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 将阻止重写。

【讨论】:

  • 太棒了;谢谢,@Anubhava! I will accept this when the option is available.我很欣赏这个解决方案。
  • 解释清楚,+1 :)
猜你喜欢
  • 1970-01-01
  • 2018-04-03
  • 2010-12-26
  • 1970-01-01
  • 2011-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
相关资源
最近更新 更多