mod_rewrite 带有问号和 & 符号(使用 PHP)

发布于 2024-09-01 21:02:51 字数 1071 浏览 0 评论 0原文

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

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

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

请注意,重写页面名称时,我也有效地“移动”了问号。当我尝试这样做时,Apache 很乐意执行此转换:

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

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

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

http://example.com/home&x=88 这样的调用将按照我的预期工作(即 pagex $_GET 变量均已正确设置)。

据我所知,差异很小,但如果可能的话,我希望我的 URL 变量以问号“开头”。我确信这反映了我自己对 mod_rewrite 重定向如何与 PHP 交互的误解,但似乎我应该能够做到这一点(以一种或另一种方式)。

预先感谢!
干杯,
-克里斯

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

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

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

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]

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]

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).

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巨坚强 2024-09-08 21:02:51

试试这个:。

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

B 转义反向引用(应该不是必需的,因为它匹配 [az]+,但如果您想稍后扩展它,它可能很有用)。

编辑:添加了 RewriteCond。
编辑 2:QSA 负责添加 & 符号。

Try this:.

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

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).

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文