Skip to content

The Nginx map module — clean redirects, decision tables, and why if is the wrong tool

How the map directive replaces brittle if chains in Nginx, builds compact redirect tables from a file, and acts as the foundation for header-based decisions.

“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

  1. Replace an if chain with a map. Old (anti-pattern):
    location / {
        if ($http_user_agent ~* "googlebot") { return 200 "ok"; }
        if ($http_user_agent ~* "bingbot")   { return 200 "ok"; }
        # ...
    }
    New:
    map $http_user_agent $is_search_bot {
        default       0;
        ~*googlebot   1;
        ~*bingbot     1;
        ~*duckduckbot 1;
    }
    
    server {
        location / {
            if ($is_search_bot) { return 200 "ok"; }
            # ...
        }
    }
  2. Redirect tables — the killer use case. Build a slug-to-URL table:
    map $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
        }
    }
    The include line pulls additional entries from a file — that file can be generated from spreadsheets or rebuilt by a CI job.
  3. Multi-source decisions. map only takes one source variable, but you can chain maps 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;
    }
  4. Use default always. 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.
  5. Map files for large data sets. A 200-line redirects.map is comfortable to maintain by hand; for a migration with 10 000 redirects, generate the file in CI from a source-of-truth CSV. Then sudo nginx -t && sudo systemctl reload nginx is the only deploy step.
  6. Reload behaviour: changes to map blocks (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.
  7. Memory cost: large maps consume memory proportional to entries. map_hash_bucket_size and map_hash_max_size may need tuning for tables of >10 000 entries:
    map_hash_bucket_size 128;
    map_hash_max_size    4096;

Common pitfalls

  • Using map inside server {} — it must be at http {} scope. Nginx errors clearly on load if you misplace it.
  • A default value 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 and mv over.
  • Forgetting hostnames; when matching $host values that contain dots — the default tokenises by dot. With hostnames; you can write example.com as 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.