Nginx map directive to specify redirection along with redirection type

nginxredirection

I got redirections working by writing this config file:

map $request_uri $new_uri {
    default https://github.com;
    /www http://wow.com;
    /?p=1 http://wow.com/p1;
}
server {
    listen 80;
    server_name TestDomain.com www.TestDomain.com;

    location / {
        if ($new_uri) {
            return 301 $new_uri;
        }
    }
}

Now, I would also like to control whether its a 301 or 302 with each redirection, so I tried doing this:

map $request_uri $new_uri {
    default https://github.com;
    /www http://wow.com;
    /?p=1 http://wow.com/p1;
}
map $request_uri $ret_code {
    default 302;
    /www 302;
    /?p=1 302;
}
server {
    listen 80;
    server_name TestDomain.com www.TestDomain.com;

    location / {
        if ($new_uri) {
            return $ret_code $new_uri;
        }
    }
}

But I can't seem to get the return statement right, it complains of invalid return code when I test the config file. How do I go about specifying the last line if I have both the return code and the url in variables?

Also, any pointers on how can I configure default to be:

map $request_uri $new_uri {
    default https://github.com$request_uri;

so that default redirection rule is set as testdomain.com/whatever to github.com/whatever?

Best Answer

I don't know how to implement the status code.

For the default option, you can try this:

map $request_uri $new_uri {
    default DEFAULT;
    ...
}

server {
    listen 80;
    server_name TestDomain.com www.TestDomain.com;

    location / {
        if ($new_uri = "DEFAULT") {
            return $ret_code https://github.com$request_uri;
        }
        if ($new_uri) {
            return $ret_code $new_uri;
        }
    }
}