2

I need to replace the values of the QueryString by using Apache mod_rewrite. Many values have to be replaced by one new value ({oldValueA1, oldValueA2} => newValueA; {oldValueB1, oldValueB2} => newValueB). The parameter appears variable times in the query_string. The order of the parameter values is random. If the redirected query_string contains a value twice, it doesn't matter for me. The request_uri is variable, but should not be change during the redirect.

Here are some examples. The first row contains the original url, the second the new one.

localhost/mag/cat/?myParameter=oldValueA1&myParameter=oldValueB1
localhost/mag/cat/?myParameter=newValueA&myParameter=newValueB

localhost/mag/?myParameter=oldValueA2
localhost/mag/?myParameter=newValueA

localhost/dig/cat/?myParameter=oldValueB1&myParameter=oldValueA2
localhost/dig/cat/?myParameter=newValueB&myParameter=newValueA

localhost/dig/?myParameter=oldValueB2&oldValueB3
localhost/dig/?myParameter=newValueB&newValueB

I tried several RewriteRules with some Conditions, but i can't find a solution for this problem. Has anyone an idea?

Thx! :)

5
  • 1
    not related: when you have several parameters they should be separated with &, not ? Commented Nov 6, 2013 at 13:30
  • rewriting query string parameters is really hard, check this answer for details stackoverflow.com/questions/7703552/rewriting-dynamic-urls/… . As you can see you will have a lot of problems (like working with not yet encoded chars), maybe you could try it in the application code instead of apache/mod_rewrite Commented Nov 6, 2013 at 13:35
  • Thx, your right about the ? and &. Copy-paste-mistake. I will change it. Commented Nov 6, 2013 at 13:50
  • If you pass localhost/mag/cat/?myParameter=newValueA&myParameter=newValueB, only the last, ie, myParameter=newValueB is passed to your CGI script. Commented Nov 6, 2013 at 19:03
  • @jacouh I tested it with the solution in my answer below and both values are passed. It works fine. Commented Nov 11, 2013 at 21:48

1 Answer 1

4

I found a solution for my problem. Maybe it will help someone else, too. Here it is:

RewriteCond %{QUERY_STRING} ^(.*[&?]|)myParameter=(oldValueA1|oldValueA2)([&?].*|)$
RewriteRule ^(.*)$ $1?%1myParameter=newValueA [R=301,NC,L]
RewriteCond %{QUERY_STRING} ^(.*[&?]|)myParameter=(oldValueB1|oldValueB2)([&?].*|)$
RewriteRule ^(.*)$ $1?%1myParameter=newValueB [R=301,NC,L]
Sign up to request clarification or add additional context in comments.

1 Comment

I think you forgot to include %2 in the rewritecond directive. This will omit any query string parameters after myParameter. Thanks for this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.