简体   繁体   English

由于URL重写,PHP $ _GET变量为空

[英]PHP $_GET variable is empty due to URL rewriting

I have rewritten a URL with .htaccess so that it looks prettier. 我用.htaccess重写了一个URL,以便它看起来更漂亮。 But when I add a query string to this URL, the keys and are not visible from PHP. 但是,当我向该URL添加查询字符串时,键和在PHP中不可见。

In my .htaccess file, I tried several things to fix the problem, but nothing worked. 在我的.htaccess文件中,我尝试了几种方法来解决此问题,但没有任何效果。

RewriteEngine On
[some code]
RewriteRule ^([a-zA-Z0-9_-]+)/?$ ?site=$1

I have tried this rewriting, to see if it works: 我尝试了这种重写,以查看是否有效:

RewriteRule ^search?q=g ?site=search&q=g

But if I print_r($_GET) in PHP, I will just get Array ( [site] => search ) Try it on http://kwtsports.bplaced.de/search?q=g . 但是,如果我在PHP中使用print_r($_GET) ,我将只得到Array ( [site] => search )http://kwtsports.bplaced.de/search?q=g上尝试一下。

I have a search field that redirects to /search?q=blablaSearchQuery , but as I said, $_GET['q'] is empty. 我有一个重定向到/search?q=blablaSearchQuery的搜索字段,但是正如我所说, $_GET['q']为空。

This also doesn't work: 这也行不通:

RewriteRule ^search?q=([a-zA-Z0-9_-]+)/?$ ?site=search&q=$1

Does anyone know why this happens? 有谁知道为什么会这样吗?

Add [QSA] to the end of your RewriteRule . [QSA]添加到RewriteRule的末尾。 This appends the old query string to the result. 这会将旧的查询字符串附加到结果中。

See the docs for more information. 有关更多信息,请参阅文档

Does anyone know, why this happens? 有谁知道,为什么会这样?

Yes. 是。 You cannot test the query string in the rewrite rule, so this part of your rule will never work: RewriteRule ^search?q=g . 您无法在重写规则中测试查询字符串,因此规则的这一部分将永远无法工作: RewriteRule ^search?q=g

If you want to test a query string, you have to test it in the rewrite cond. 如果要测试查询字符串,则必须在重写条件中对其进行测试。

For example, for your RewriteRule ^search?q=g?site=search&q=g example, you would have to do something like this: 例如,对于您的RewriteRule ^search?q=g?site=search&q=g示例,您将必须执行以下操作:

RewriteCond %{QUERY_STRING} ^q=([^&]+)
RewriteRule ^search/?$ site=search&q=%1 [L]

In this particular case, since you are not wanting to change the q value, we don't really need to test it, and you could simply pass it through with the QSA option after adding site=search : 在这种特殊情况下,由于您不想更改q值,因此我们实际上不需要测试它,您可以在添加site=search之后简单地使用QSA选项将其传递:

RewriteRule ^search/?$ site=search [L,QSA]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM