Replacing a querystring parameter value using mod_rewrite

时间秒杀一切 提交于 2020-01-20 05:09:07

问题


I would like to map this:

http://www.example.com/index.php?param1=value1&param2=value2&param3=value3 (etc. ad infinitum)

to

http://www.example.com/index.php?param1=newvalue1&param2=value2&param3=value3 (etc.)

In other words, just change the value of a single parameter in the query string. I know what the old value is, so I am trying to match the exact text index.php?param1=value1 and replace it with index.php?param1=newvalue1. I cannot seem to find any examples on how to do this using mod_rewrite. Any assistance greatly appreciated.


回答1:


Try this rule:

RewriteCond %{QUERY_STRING} ^(([^&]*&)*)param1=value1(&.*)?$
RewriteRule ^index\.php$ /index.php?%1param1=newvalue1%3 [L,R=301]



回答2:


this is kind of a brittle solution in that it depends on the order of the GET params but it works for your specific example, preserves any GET args after param1 and also preserves POST args:

RewriteCond %{QUERY_STRING} param1=value1(&.*)*$
RewriteRule ^/index\.php$ /index.php?param1=newvalue1%1 [L]

I have a little test php page that just does print_r($_GET) and print_r($_POST) and using curl from the command line with post args i see the following:

$ curl --data "post1=postval1&post2=postval2" "http://www.example.com/index.php?param1=value1&param2=value2&param3=value3"
_GET
Array
(
    [param1] => newvalue1
    [param2] => value2
    [param3] => value3
)

_POST
Array
(
    [post1] => postval1
    [post2] => postval2
)

if you wanted the rewrite condition to be more flexible you could add some conditional patterns like Gumbo did but it would be good to know exactly what conditions you need to handle (i.e. can param1 be in any position, can it be the only get arg, etc.)

edit for new requirements below

the following seems to work for replacing "value1" with "newvalue1" anywhere in the query string or the url (but not in post'ed keys/values):

RewriteCond %{QUERY_STRING} ^(.*)value1(.*)$
RewriteRule ^(.*)$ $1?%1newvalue1%2 [L]

RewriteRule ^(.*)value1(.*)$ $1newvalue1$2 [L]

%N is used for substituting values from the RewriteCond while $N is used for substituting values from the RewriteRule itself. just used two RewriteRules, one of them with the associated RewriteCond to handle the query string.



来源:https://stackoverflow.com/questions/1497184/replacing-a-querystring-parameter-value-using-mod-rewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!