20

I have an URL of this type:

http://www.example.com/?param1=val1&param2=&param3=val3&param4=val4&param5=val5

And I want to redirect it to this one:

http://www.example.com/newparam/val3/val4

So I have tried this rewrite rule with no success:

rewrite "/?param1=val1&param2=&param3=(.+)&param4=(.+)&param5=(.+)" http://www.example.com/newparam/$1/$2 redirect;

Is nginx not able to deal with query parameters?

EDIT: I don't want to rewrite all petitions. I only need to rewrite that URL, without affecting the others.

coviex
  • 105
  • 3
David Morales
  • 685
  • 1
  • 5
  • 14

2 Answers2

19

Ok, thanks to the initial help of rzab, I have redefined his rule to this working solution:

location / {
    if ($args ~* "/?param1=val1&param2=&param3=[0-9]+&param4=.+&param5=[0-9]+") {
        rewrite ^ http://www.example.com/newparam/$arg_param3/$arg_param4? last;
    }
}

I just added a condition to avoid infinite recursion, and a ? at the end of the rule to get rid of the initial params. It works perfectly :)

sebix
  • 4,175
  • 2
  • 25
  • 45
David Morales
  • 685
  • 1
  • 5
  • 14
5
location = / {
  rewrite ^ http://www.example.com/newparam/$arg_param3/$arg_param4;
}
rzab
  • 266
  • 1
  • 2
  • So, must I write $arg_ and then the parameter name? – David Morales Jul 15 '10 at 18:36
  • Yes, that would be the easiest. – Martin Fjordvald Jul 15 '10 at 19:36
  • Ok, but I don't want to rewrite all petitions. I only need to rewrite that URL, without affecting the others. – David Morales Jul 16 '10 at 07:59
  • I have made some tests. That rule will generate an infinite redirection. I will write a new answer with the code I got to work. Thanks :) – David Morales Jul 16 '10 at 08:13
  • I should probably mention, that you have to declare "location /" besides "location = /" to avoid recursion. I guess you'll have it to proxy_pass somewhere as the main route. "location = /" matches exactly / requests. Anyway, matching $args seems ok, except it'll match _any_ request with the parameters ?param1=val1&.... – rzab Jul 16 '10 at 08:45
  • A bit more explanation in the answer would be helpful. – Felix Sep 28 '21 at 15:46