Nginx: redirect from old url to new one and keep query string

nginxrewrite

I need to rewrite old urls to new ones using nginx rewrite. I have one problem with query string. Redirection does not work if old url has query string parameter. My current config:

map $request_uri $newuri {
    /old-url/path /new-url/path;
}

server {
    location / {
        if ($newuri) {
            return 301 $newuri;
        }
    }
}

Best Answer

Your map statement is performing a string match on $request_uri. The variable $request_uri also includes the query string. If you want to match with and without the query string, you should match only the front of $request_uri, which can be accomplished using regular expression syntax:

map $request_uri $newuri {
    ~*^/old-url/path /new-url/path;
}

See this document for details.