how to do nginx rewrites from a url with get parameters

3.3k Views Asked by At

This is my first ever StackOverflow question so please bear with me.

Nginx serves many different sites for us and we have a lot of redirects from migrating clients from different vendors and such. We have set up an /includes directory that houses redirect files for each domain that we migrate over. Occasionally, we will need to write redirects from a url that contains get parameters:

http://example.com/content/default.aspx?NewsId=28

To do this, we have been doing this in an nginx /includes file called example.com-redirects

location ^~ /content/default.aspx {
    if ($args ~ "NewsId=28") { rewrite ^ http://example.com/news? permanent; break; }
    # add more statements like the one above
}

That has worked just fine for us thus far. Unfortunately, we need to do the same thing but for a different domain that could have the same get parameters. And of course nginx doesn't allow for duplicate locations.

location ^~ /content/default.aspx {
    if ($args ~ "NewsId=28") { rewrite ^ http://differentexample.org/news? permanent; break; }
}

I've tried a couple of different solutions all giving me syntax errors. No one at my company is an nginx expert anymore so I could really use some help solving this. I have added an if ($host ~ "example.com") within the location block and that gave me an error. And I've tried adding the location block within the if ($host ~ "example.com") block. Both times nginx told me that I can't put that there.

I usually find my answer in the vast knowledge base that is the internet but seem to be striking out on a solution for this and we're running out of time before we launch this client.

1

There are 1 best solutions below

0
On

Instead of using if, use a variable. In the virtual host config you set this variable. In the include with the location you use it:

server {
    ...
    set $redirect_host "example.org";
    include /includes/news28.conf;
    ...
}

# include part
location /foo {
    if ($args ~ "NewsId=28") { rewrite $scheme://$redirect_host/news? permanent; }
}

Of course you need to set that variable also in the server config of the host already using this include. Hope this helps.