Anand Singh

Posted on March 9th

A Quick Guide Of Map in Nginx And How To Use It

"What is map, seen in nginx configuration files? how to use to make conditional variables in nginx configuration"

If you are a new DevOps engineer, you might have seen and wondered what is map in Nginx

A basic map statement in Nginx looks like the following.

map $http_x_forwarded_proto $new_https {
    default "";
    "https" on;
    "xyz" off;
}

Let me help you with this. The explanation is quite easy.

You can read this statement as the following  

map $existing_variable $new_variable {
    default "default_value_for_new_variable";
    "condition1" value1; //if value of $existing_variable is "condition1", store "value1" in $new_variable
    "condition2" value2; //and so on....
}

A map statement in nginx starts with  map, followed by 2 variables names that begin with a $ sign, just like in PHP.

In this case, those two variables are $http_x_forwarded_proto and $new_https

Next, the code inside braces is basically a switch statement.

It matches the value of $http_x_forwarded_proto with first word in the statement, and if the match is found, value of $new_https set to second word of the statement.

Take the following example:

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;
    }
 }

This configuration will change /old.html in $uri to /index.html.

Nginx maps support regular expressions too, here is an example on how to use them.  

map $request_uri $uri_only {
    "~^(?<u>[^?]+)?(?:.*)?"  $u;
    default                    $request_uri;
}

Hope this helps with your understanding of Nginx maps.

Feel free to comment to ask or discuss anything related to Nginx maps.

Cheers!
Anand

Comments

Leave a comment.

Share your thoughts or ask a question to be added in the loop.