Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a querystring parameter value using mod_rewrite

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.

like image 279
Russ Avatar asked Sep 30 '09 10:09

Russ


2 Answers

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.

like image 39
jnichols959 Avatar answered Sep 29 '22 09:09

jnichols959


Try this rule:

RewriteCond %{QUERY_STRING} ^(([^&]*&)*)param1=value1(&.*)?$
RewriteRule ^index\.php$ /index.php?%1param1=newvalue1%3 [L,R=301]
like image 192
Gumbo Avatar answered Sep 29 '22 08:09

Gumbo