brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: one nginx map handles a long list of old URLs to redirect

Nginx
~/tips/tip-nginx-map-redirect-list

map $request_uri $new_uri {

Keeps hundreds of old-to-new redirects in one lookup table instead of many location blocks.

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)

More Nginx tips sudo certbot --nginx -d example.com -d www.example.com /data/nginx/custom/server_redirect.conf map $http_upgrade $connection_upgrade { proxy_intercept_errors on; proxy_redirect http://localhost:3000/ /app/; All Nginx tips (50) All topics

Link