本文介绍了带问号和&符的mod_rewrite(对于PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于PHP的Web应用程序,正在尝试将Apache的mod_rewrite应用到该应用程序.

I have a PHP-based web app that I'm trying to apply Apache's mod_rewrite to.

原始URL的格式为:
http://example.com/index.php?page=home&x= 5

Original URLs are of the form:
http://example.com/index.php?page=home&x=5

我想将它们转换为:
http://example.com/home?x=5

And I'd like to transform these into:
http://example.com/home?x=5

请注意,在重写页面名称时,我也有效地移动"了问号.当我尝试执行此操作时,Apache会愉快地执行以下翻译:

Note that while rewriting the page name, I'm also effectively "moving" the question mark. When I try to do this, Apache happily performs this translation:

RewriteRule ^/([a-z]+)\?(.+)$ /index.php?page=$1&$2  [NC,L]

但是它弄乱了PHP中的$_GET变量.例如,对http://example.com/home?x=88的调用仅产生一个$_GET变量(page => home). x => 88去哪里了?但是,当我更改规则以使用&"号而不是问号时:

But it messes up the $_GET variables in PHP. For example, a call to http://example.com/home?x=88 yields only one $_GET variable (page => home). Where did x => 88 go? However, when I change my rule to use an ampersand rather than a question mark:

RewriteRule ^/([a-z]+)&(.+)$ /index.php?page=$1&$2  [NC,L]

http://example.com/home&x=88这样的调用将按我期望的那样工作(即pagex $ _GET变量均已适当设置).

a call like http://example.com/home&x=88 will work just as I'd expect it to (i.e. both the page and x $_GET variables are set appropriately).

我知道区别很小,但是如果可能的话,我希望我的URL变量以问号开始".我敢肯定,这反映了我对mod_rewrite重定向如何与PHP交互的误解,但看来我应该能够做到(一种或另一种方式).

The difference is minimal I know, but I'd like my URL variables to "start" with a question mark, if it's possible. I'm sure this reflects my own misunderstanding of how mod_rewrite redirects interact with PHP, but it seems like I should be able to do this (one way or another).

提前谢谢!
干杯,
-克里斯

Thanks in advance!
Cheers,
-Chris

推荐答案

尝试一下:.

RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^/([a-z]+)(?:$|\?(?:.+)) /index.php?page=$1 [NC,L,B,QSA,NE]

B转义了反向引用(由于它与[a-z] +匹配,因此没有必要,但是如果以后要扩展它,可能会很有用).

B escapes the backreference (shouldn't be necessary since it is matching [a-z]+, but in case you want to extend it later, it might be useful).

添加了RewriteCond.QSA负责添加&符.

added RewriteCond.EDIT 2: QSA takes care of adding the ampersand.

这篇关于带问号和&符的mod_rewrite(对于PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 05:28