Variables, map & split_clients
Nginx's configuration is declarative: it has no functions or loops, and if is fragile. Decisions that depend on the request ("is this origin allowed?", "is this client internal?", "which 10 % of users get the canary?") are made with lookup tables that compute a new variable from an existing one. There are three: map, geo and split_clients. All are defined in the http context and evaluated lazily, only when the variable is used, so an unused map costs nothing.
map
map $source $result { … } compares $source with each line and sets $result:
| Line | Matches |
|---|---|
default value; |
when nothing else matches (otherwise the result is empty) |
exact value; |
exact string |
~regex value; / ~*regex value; |
regex (case-sensitive / insensitive); captures can be used in the value |
hostnames; |
allows *.example.com style masks in the source values |
Exact strings are checked first, then regexes in order. A typical use is a CORS allow-list: answer with Access-Control-Allow-Origin only for origins you trust, which a plain add_header cannot do:
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
access_log off;
map $http_origin $cors_origin {
default "";
"https://shop.example" $http_origin;
~^https://[a-z0-9-]+\.shop\.example$ $http_origin;
}
map $request_method $is_preflight {
OPTIONS 1;
default 0;
}
server {
listen 127.0.0.1:8080;
location /api/ {
add_header Access-Control-Allow-Origin $cors_origin always; # an empty value: no header at all
add_header Vary Origin always;
if ($is_preflight) { return 204; }
return 200 "data\n";
}
}
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
for o in https://shop.example https://admin.shop.example https://evil.example; do
h=$(curl -s -D - -o /dev/null -H "Origin: $o" 127.0.0.1:8080/api/x | grep -i '^access-control' | tr -d '\r')
echo "Origin: $o -> ${h:-(no CORS header)}"
done
curl -s -o /dev/null -w "preflight: %{http_code}\n" -X OPTIONS -H "Origin: https://shop.example" 127.0.0.1:8080/api/x
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/nullOrigin: https://shop.example -> Access-Control-Allow-Origin: https://shop.example
Origin: https://admin.shop.example -> Access-Control-Allow-Origin: https://admin.shop.example
Origin: https://evil.example -> (no CORS header)
preflight: 204
Nginx skips add_header when its value is empty, so the untrusted origin gets no CORS header at all, and the browser blocks the response. Vary: Origin tells caches that the response differs per origin; forgetting it lets a cache serve one origin's answer to another.
geo: decisions by client address
geo is a map for IP addresses with CIDR ranges and longest-prefix matching. By default it uses $remote_addr; you can name another variable as the source. Typical uses: skip rate limits for internal networks, show an admin area only to the VPN, tag traffic from a partner. The session feeds the address from a query argument, because every request inside the sandbox comes from 127.0.0.1:
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
access_log off;
geo $arg_ip $network { # in production: geo $network { … } (uses $remote_addr)
default public;
10.0.0.0/8 internal;
10.20.0.0/16 vpn;
192.0.2.17/32 partner;
}
map $network $limit_key { # internal clients get an empty key: limit_req ignores them
internal "";
vpn "";
default $arg_ip;
}
server {
listen 127.0.0.1:8080;
location / { return 200 "$arg_ip is $network, rate-limit key '$limit_key'\n"; }
}
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
for ip in 10.1.2.3 10.20.5.6 192.0.2.17 198.51.100.4; do curl -s "127.0.0.1:8080/?ip=$ip"; done
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null10.1.2.3 is internal, rate-limit key ''
10.20.5.6 is vpn, rate-limit key ''
192.0.2.17 is partner, rate-limit key '192.0.2.17'
198.51.100.4 is public, rate-limit key '198.51.100.4'
10.20.5.6 is inside both 10.0.0.0/8 and 10.20.0.0/16; the longer prefix wins. Chaining geo into map is the standard way to exempt networks from rate limiting: requests whose key is empty are not counted.
Behind a load balancer, $remote_addr is the balancer's address. The realip module (set_real_ip_from 10.0.0.0/8; real_ip_header X-Forwarded-For; real_ip_recursive on;) replaces it with the client address from the header, but only for requests coming from the trusted range.
split_clients: percentages
split_clients hashes a string (MurmurHash2) and assigns it to buckets by percentage. The same input always lands in the same bucket, which makes it right for A/B tests and canary releases keyed by a user id or cookie:
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
access_log off;
split_clients "canary-v2-${arg_user}" $release {
10% canary;
* stable;
}
server {
listen 127.0.0.1:8080;
location / { return 200 "$release\n"; }
}
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
for u in $(seq 1 1000); do curl -s "127.0.0.1:8080/?user=u$u"; done | sort | uniq -c
echo "user u42 twice: $(curl -s '127.0.0.1:8080/?user=u42') $(curl -s '127.0.0.1:8080/?user=u42')"
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null 103 canary
897 stable
user u42 twice: stable stable
About 10 % of users got the canary, and user u42 stays in its bucket on every request. The canary-v2- prefix is a salt: change it for the next experiment and users are reshuffled, so the same 10 % don't always get every risky release. In a proxy, the variable typically selects an upstream: proxy_pass http://$release; with upstream stable { … } and upstream canary { … }.
Test yourself
Why compute the CORS header value with map instead of writing add_header Access-Control-Allow-Origin $http_origin;?
- map is faster
- Echoing any Origin allows every website; map returns the origin only if it is on the allow-list, and an empty value suppresses the header
- add_header can't use variables
- Browsers require map
geo has 10.0.0.0/8 internal; and 10.20.0.0/16 vpn;. What is 10.20.1.1?
- internal
- vpn: the longest matching prefix wins
- both
- default
What makes split_clients suitable for canary releases?
- It is random per request
- It hashes a stable key (user id, cookie), so each user always lands in the same bucket while the buckets have the configured percentages
- It reads the server load
- It uses cookies automatically