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_variablebased on$source_variable.- Inside the braces, list
key value;pairs wherekeymatches$source_variablevalues. - Use
defaultto 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
mapoutside thehttpblock causes errors. - Using regex keys requires the
~or~*prefix for case-sensitive or insensitive matching. - Not specifying a
defaultvalue can lead to empty variables. - Trying to use
mapinsideserverorlocationblocks 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
| Directive | Description | Example |
|---|---|---|
| map | Creates a variable based on another variable's value | map $http_user_agent $is_mobile { default 0; ~*Mobile 1; } |
| default | Fallback value if no keys match | default 0; |
| ~* | Case-insensitive regex match | ~*Mobile 1; |
| Usage location | Must be inside http block | http { 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.