Thinking outside of the box with NGINX series - map command

I don’t think this is thinking outside the box, but I could not do a series of posts about useful commands without talking about map, arguably one of the most useful commands on NGINX, especially that I’m sure map will be used in most of our posts. You should think about map as a “switch” statement like many programming languages have, it’s how you will be able to take advantage of it.

Basically, the syntax for map is the following:

map $variable_to_evaluate $return_variable { 
    value_to_match value_to_return; 
    default value_to_return_by_default;

Where the variable_to_evaluate can be ANY variable accessible by NGINX, which includes HTTP headers, Cookies, etc.

You can think of map as a good substitute for most “ifs” that you plan to use, especially considering that if is evil, basically map is a safe replacement for if in most of the situations.

Let’s review our rate limiting example that we used geo to create a whitelist, now we will use map to do the same thing, if the client sends a cookie called “whitelistrl”, he will bypass the rate limiting, but remember, this is not a good idea for rate limiting control as cookies can be easily injected to any HTTP request.

Another functionality is that map can be nested, one map can call another map or even combine geo/map/split_clients.

Let’s try another example, what about using map and geo to allow us to only whitelist clients from our customer network that contains the whitelistrl cookie? Sounds like fun!

One thing to note thou, the order of the nesting matters, map accepts nesting other commands, but this is not true for all commands, for example, if we had tried to call map from geo, it was not going to work, so always test before deploying to production!

Also, you can see examples of map usage in posts right here on my blog!

Some examples are:

See you on the next post! 

If you have any question or suggestion, use the Ask-O-matic link on the top of the page.