0
0
NginxHow-ToBeginner · 4 min read

How to Use map Directive in Nginx for Conditional Variables

Use the map directive in Nginx to create a new variable whose value depends on the value of another variable. Define map in the http block with key-value pairs, then use the new variable in your server or location blocks.
📐

Syntax

The map directive defines a variable based on the value of another variable. It is placed inside the http block. The syntax is:

  • map $source_variable $new_variable { ... }: Defines a new variable $new_variable based on $source_variable.
  • Inside the braces, list key value; pairs where key matches $source_variable values.
  • Use default to specify a fallback value.
nginx
map $http_user_agent $is_mobile {
    default 0;
    ~*Mobile 1;
}
💻

Example

This example detects if the user agent contains "Mobile" and sets a variable $is_mobile to 1 or 0. Then it uses this variable to serve different root directories.

nginx
http {
    map $http_user_agent $is_mobile {
        default 0;
        ~*Mobile 1;
    }

    server {
        listen 80;

        location / {
            root /var/www/html/desktop;
            if ($is_mobile) {
                root /var/www/html/mobile;
            }
        }
    }
}
Output
When a request comes with a user agent containing "Mobile", Nginx sets $is_mobile to 1 and serves files from /var/www/html/mobile; otherwise, it serves from /var/www/html/desktop.
⚠️

Common Pitfalls

  • Placing map outside the http block causes errors.
  • Using regex keys requires the ~ or ~* prefix for case-sensitive or insensitive matching.
  • Not specifying a default value can lead to empty variables.
  • Trying to use map inside server or location blocks is invalid.
nginx
http {
    # Wrong: map inside server block (causes error)
    server {
        # map directive is not allowed here and will cause an error
    }

    # Right: map inside http block
    map $http_host $new_var {
        default "value";
    }
}
📊

Quick Reference

DirectiveDescriptionExample
mapCreates a variable based on another variable's valuemap $http_user_agent $is_mobile { default 0; ~*Mobile 1; }
defaultFallback value if no keys matchdefault 0;
~*Case-insensitive regex match~*Mobile 1;
Usage locationMust be inside http blockhttp { map ... }

Key Takeaways

Use the map directive inside the http block to create conditional variables.
Always include a default value to avoid empty variables.
Regex keys in map require ~ or ~* prefixes for matching.
Do not place map inside server or location blocks.
Use the mapped variable later in server or location blocks for flexible config.