NGINX 301 Redirect a URL with parameters to new URL

301-redirectnginxubuntu-12.04

I've deployed a site live and trying to redirect some of the original URLs to the new URLs. I'm fairly new with NGINX configuration on redirects like this.

This one works:

location /contactus.aspx {
    return 301 $scheme://$host/contacts;
}

These do not work (The url results in a 404 and does not redirect):

location /productcatalog.aspx?directoryid=11 {
    return 301 $scheme://$host/hard-drive-cases;
}
location /productdetails.aspx?productid=26* {
    return 301 $scheme://$host/lto-5-blue;
}

I've already service nginx reload successfully without error.

The biggest difference between the redirects that do work and the redirects that do not work are the added parameters. What is the best way to redirect URLs with parameters (and a wild card at the end) so that it will work properly?

Best Answer

The location directive does not match on the query string. So you'll have to do something else.

I presume you have a large number of these to work with, so I would suggest using a couple of maps. For instance:

map $arg_directoryid $mycategory {
    11 hard-drive-cases;
    12 some-other-category;
    default ""; # would go to the homepage, change it to go to some other page
}

Then you would do a location such as:

location /productcatalog.aspx {
    return 301 $scheme://$host/$mycategory;
}

Make a second map and location for the $arg_productid corresponding to productdetails.aspx. If that one is exceptionally large, though, you might have performance issues, and need to scrap this and do some scripting to obtain the redirect from a database.

The maps must be in your http block, not within a server block. If you are hosting multiple sites, the best place to put them, in my opinion, is immediately before the server block that they correspond to.