Redirect based on parameter

Moon asked:

I’m trying to redirect a page based on the parameters passed.

I would like redirect

rewrite ^/join_trial to /test? permanent;

and

rewrite ^/join_trial?discount=free(.*) /test2? permanent;

The first one works, but the second one doesn’t. It looks like nginx doesn’t take (.*) regex.

For the first one, the following cases work.

/join_trial?test=aaaaa

/join_trial?923849=aaa

Basically, you can put anything after /join_trial.

I want to have a redirect when a user appends ?discount=free(anything goes here).

Is this possible with nginx?

My answer:


You can’t match on a query string at all in a rewrite. So you’ll need to check the argument directly.

For instance:

if ($arg_discount ~ ^free) {
    rewrite ^/join_trial /test2? permanent;
}
rewrite ^/join_trial /test? permanent;

And I suspect you really do not want to be sending 301 redirects, as the user will then see /test or /test2 right in their address bar. Perhaps you really mean to process these URLs internally only? In that case change permanent to last.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.