“If is evil” is the most-cited piece of Nginx folklore for a reason: inside a location block, if evaluates per request and interacts weirdly with rewrite. The map directive is the right tool for the same use cases — building a variable from another variable via a lookup table. Once you start using map, half your ifs disappear and the config gets easier to reason about.
How to verify
See where map and if are used today:
sudo nginx -T | grep -E '^\s*(map |if \()' | head
sudo nginx -T | grep -E 'rewrite ' | head
nginx -V 2>&1 | tr ' ' '\n' | grep map_module
if blocks inside location are the suspects to migrate. map blocks live at http {} scope.
What’s happening
map $source_variable $target_variable { ... } creates a hash table at config-load time. When $target_variable is read at request time, Nginx looks up $source_variable in the table and assigns the matching value to $target_variable. Lookups are O(1) on exact matches; supports regex (~), case-insensitive (~*), and defaults.
The big difference from if: map is evaluated lazily and once per request when the target variable is first read. if is evaluated every time the block is hit and changes context (it implicitly creates a nested location). map is also much faster for large tables — a 10 000-entry redirect map is constant time, while a chain of ifs is linear.
map files can be loaded from disk via the include directive inside the block, so you can keep a 5 000-line redirect table in its own file and reload Nginx to update it.
The procedure
- Replace an
ifchain with amap. Old (anti-pattern):
New:location / { if ($http_user_agent ~* "googlebot") { return 200 "ok"; } if ($http_user_agent ~* "bingbot") { return 200 "ok"; } # ... }map $http_user_agent $is_search_bot { default 0; ~*googlebot 1; ~*bingbot 1; ~*duckduckbot 1; } server { location / { if ($is_search_bot) { return 200 "ok"; } # ... } } - Redirect tables — the killer use case. Build a slug-to-URL table:
Themap $request_uri $new_url { hostnames; default ""; /old-product-page /products/widget-v2; /press /about/press; /docs /knowledge-base; /support /contact?path=support; include /etc/nginx/conf.d/redirects.map; } server { location / { if ($new_url) { return 301 $new_url; } # normal handling } }includeline pulls additional entries from a file — that file can be generated from spreadsheets or rebuilt by a CI job. - Multi-source decisions.
maponly takes one source variable, but you can chainmaps through intermediate variables:map $http_x_country $maybe_block_country { default 0; CN 1; RU 1; } map $request_uri $is_sensitive { default 0; /admin 1; ~^/api/ 1; } map "$maybe_block_country:$is_sensitive" $block_request { default 0; "1:1" 1; } - Use
defaultalways. Without it, the target variable becomes empty string on a miss, which then truthy-checks like an empty string — usually what you want, but explicit is better. - Map files for large data sets. A 200-line
redirects.mapis comfortable to maintain by hand; for a migration with 10 000 redirects, generate the file in CI from a source-of-truth CSV. Thensudo nginx -t && sudo systemctl reload nginxis the only deploy step. - Reload behaviour: changes to
mapblocks (and included files) only take effect on reload. The hash table is built at load time, so a fresh reload is required for any change. - Memory cost: large maps consume memory proportional to entries.
map_hash_bucket_sizeandmap_hash_max_sizemay need tuning for tables of >10 000 entries:map_hash_bucket_size 128; map_hash_max_size 4096;
Common pitfalls
- Using
mapinsideserver {}— it must be athttp {}scope. Nginx errors clearly on load if you misplace it. - A
defaultvalue that does not match the variable type expected downstream. Returning empty string on miss when the consumer expects a numeric flag will silently set things to zero. - Map “wins” by first match in the order written for exact keys, but regex keys are checked top-to-bottom — order them with the most specific first.
included map files that are not generated atomically. A partial-write during reload gives Nginx half a redirect table. Write to a temp file andmvover.- Forgetting
hostnames;when matching$hostvalues that contain dots — the default tokenises by dot. Withhostnames;you can writeexample.comas a key directly.
In the engagements we run, redirect tables are owned in git and templated into the map file by CI. A change to a CSV in the source repo produces a pull request, the diff is reviewed, and the reload is one command. Stack Harbor wraps this into managed operations so a marketing team can ship redirects without touching Nginx config by hand.