Replacing if with map in nginx
if inside location has surprising semantics — the documentation has a section titled "If is Evil". Most uses can be a map:
map $http_user_agent $is_bot {
default 0;
~*(bot|crawler|spider) 1;
}
map $request_uri $redirect_to {
~^/old/(.*)$ /new/$1;
default "";
}
map lives in the http block and produces a variable usable in location, proxy_set_header or return, without if's scoping traps.
Typical replacements: route by user agent to different upstreams; redirect old paths with map plus return 301 $redirect_to; select a certificate per $ssl_server_name.
A few cases still need if, such as pairing with limit_except, but they are rare.