The Nginx Map Function

Clean up your nginx configs with the nginx map function.

What is the nginx map function?

Nginx Map map allows you to mass assign a input variable to a certain outcome variable.

The below runs through all the redirects and checks if the current url is among the ones to redirect, if it is a variable called $new_uri is defined, further down we check if the variable is defined, and redirect if so.

map $uri $new_uri {

    /old.html /index.html;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;


    # Old website redirect
    if ($new_uri) {
        rewrite ^ $new_uri permanent;
    }
}

If you have a lot of redirects you can also create mapping files

map $uri $new_uri

 {
    include /etc/nginx/redirects.map;
 }

and in /etc/nginx/redirects.map;

^/products.html$ /offer.html redirect;

^/services.html$ /offer.html permanent;

^/about-us.html$ /about.html permanent;

^/another.html$ /another-new.html redirect;

^/another-another.html$ /another-another-new.html permanent;

^/another-another-another.html$ /another-another-another-new.html redirect;

The reason why the map function is used is to avoid something like this, if you have alot of redirects this can quickly get out of hand.

rewrite ^/products.html$ /offer.html redirect;
rewrite ^/services.html$ /offer.html permanent;
rewrite ^/about-us.html$ /about.html permanent;
rewrite ^/another.html$ /another-new.html redirect;
rewrite ^/another-another.html$ /another-another-new.html permanent;
rewrite ^/another-another-another.html$ /another-another-another-new.html redirect;