Nginx rewrite map with query strings

nginxregexweb-server

I have a large rewrite-map.conf file which contains a number of redirects for a server however this does not work if there is a query string variable in the URL.

For example my /etc/nginx/conf.d/redirect-map.conf contains the following:

map $request_uri $redirect_uri {
/docs/oldurlone /documents/newurlone
/docs/oldurltwo /documents/newurltwo
/docs/oldurlthree /documents/newurlthree
}

In my nginx server config I have the following config doing the redirect

if ( $redirect_uri ) {
return 302 $redirect_uri;
}

So going to https://example.com/docs/oldurlone redirects nicely to https://example.com/documents/newurlone

My issue is that should the original url contain a query string also, I'd want that to get passed through.

If I entered:
https://example.com/docs/oldurlone/?affiliatenumber27&name=dave

then I would want this to pass through to
https://example.com/documents/newurlone/?affiliatenumber27&name=dave

I have a feeling I need to do some regex somewhere but I'm firstly not sure exactly where (eg which config file this needs going in).

If anyone can help me, that would be fantastic.

Best Answer

as per NGINX docs, $request_uri does contain query string: http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_uri

so you need to strip it before you pass it to your map:

map $request_uri $request_uri_path {
  "~^(?P<path>[^?]*)(\?.*)?$"  $path;
}

and then you can use your map as follows:

map $request_uri_path $redirect_uri {
/docs/oldurlone /documents/newurlone
/docs/oldurltwo /documents/newurltwo
/docs/oldurlthree /documents/newurlthree
}

see see https://stackoverflow.com/a/43749234/1246870 for the stripping args piece.

Related Topic