mod_rewrite 删除一个 GET 变量 [英] mod_rewrite remove a GET variable

查看:14
本文介绍了mod_rewrite 删除一个 GET 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力

example.com/home?lang=fr&foo=bar

example.com/home?lang=fr&foo=bar

并重定向到

example.com/fr/home?foo=bar

example.com/fr/home?foo=bar

我试过了

    RewriteCond %{QUERY_STRING} lang=([a-z]{2})&?
    RewriteRule ^(.*) /%1/$1 [R=307]

但是我得到了一个重定向循环.这是因为 'fr' 移到请求字符串的前面后,lang=fr 不会从查询字符串中删除.这导致:

but I get a redirect loop. This is because the lang=fr is not taken away from the query string after 'fr' is moved to the front of the request string. This results in:

example.com/fr/fr/fr/fr/fr/fr/fr/fr/fr/....

example.com/fr/fr/fr/fr/fr/fr/fr/fr/fr/....

我可以使用

    RewriteRule ^(.*) /%1/$1? [R=307]

但这也从我想保持完整的查询字符串中删除了 foo=bar

but that also removes the foo=bar from the query string which I want to keep intact

我找不到从查询字符串中只删除一个变量的方法.我确定有一个简单的解决方案,但谷歌没有帮助.谢谢

I cannot find a way of removing just one variable from the query string. I'm sure there is a simple solution but google hasn't helped. Thanks

推荐答案

补充@whoisgregg answer (+1),这是一个很好的改编自 apache wiki.那里的规则并不完全很好(例如这个页面上通过查询字符串的访问控制不会抵抗一点点urlencoding).

In complement to @whoisgregg answer (+1), which is a nice adaptation from the apache wiki. Rules there are not complelty nice (for example the access control by query string on this page would'nt resist on a little urlencoding).

我们有针对测试用例的有效解决方案,但一些扩展测试可能会失败:

We have a working solution for the test case, but some extended tests may fail:

RewriteCond %{QUERY_STRING} ^(.*)lang=([a-z]{2})&?(.*)$
RewriteRule (.*) /%2/$1?%1%3 [R=307]

foo.php?foo=bar&novlang=fr&toto=titi => /fr/foo.php?foo=bar&novtoto=titi

这里检测到 lang= 部分,但如果任何参数以 lang 结尾,你就会遇到问题.

Here the lang= part is detected but if any parameter ends with lang you'll have a problem.

所以,我们需要一些修复,我这周一直在研究这个主题,我认为这是一个更好的版本:

So, we need some fix, I've been working on that subject this week and here's a better version I think:

RewriteCond %{QUERY_STRING} (.*)(^|&|%26|%20)lang(=|%3D)([^&]+)(.*)$
RewriteRule (.*) /%4/$1?%1%5 [R=307]

foo.php?foo=bar&novlang=fr&toto=titi => not matched (normal, no lang=)
foo.php?foo=bar&lang=fr&toto=titi&b=a => fr/foo.php?foo=bar&toto=titi&a=b

这里唯一悬而未决的问题是 lang 可能是部分或完全 url 编码的并且不会被检测到,但这是一种罕见的情况.我也取消了对 lang 值只有 2 个字符的控制.我认为 ([^&]+) 更好,这意味着所有字符,直到我匹配 &.

The only problem pending here is that lang could be partially or completly url encoded and would not be detected, but that's a rare case. I alos removed the control of having only 2 chars on the lang value. I think ([^&]+) is better, it means all characters until I match an &.

这篇关于mod_rewrite 删除一个 GET 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆