After a site move you often have a list of old URLs that need a 301 to their new place. Writing a location with return 301 for each one gets long and slow to read. A map keeps them in one table.
map $request_uri $new_uri {
default "";
/old-blog/ /blog/;
/about-us.html /about/;
~^/docs/v1/(.*)$ /docs/v2/$1;
}
server {
if ($new_uri) {
return 301 $new_uri;
}
...
}
Exact strings are looked up in a hash, which stays fast with thousands of entries. Lines starting with ~ are regexes, and their captures work in the new value. So /docs/v1/a/b?x=1 goes to /docs/v2/a/b?x=1. For a long list, put the entries in a separate file and use include /etc/nginx/redirects.map; inside the map block.
The if with only a return inside is one of the uses the nginx wiki calls safe, so this is not the dangerous kind of if.
Watch out with the query string. $request_uri includes it, so /old-blog/?utm_source=x does not match the exact line /old-blog/. If old links carry tracking parameters, map on $uri instead, which has no query string, and add $is_args$args to the return. $uri is also decoded and normalized, which can matter for URLs with spaces or encoded characters. I’d test a few real old links with curl -I before you trust the list.
Further reading: ngx_http_map_module
Going deeper: 🛜 Guide: AdGuard Home + Tailscale (Secure Split-Horizon DNS)