Nginx 301 Redirect Map Configuration

When a site moves or restructures, every old URL needs a permanent redirect to its new home, or visitors and search engines hit a 404. A list of a few hundred redirects belongs in a map, not a few hundred location blocks.

A map scales better than rewrite rules

A map block looks the requested path up in a hash table once per request, so a long list costs almost nothing. Exact-match keys also avoid the accidental prefix matches that a rewrite regex or a plain Apache Redirect produces. nginx needs the status code to be a literal in the return directive, so the generator emits one map per status code in use.

map $uri $redirect_301 {
    default "";
    "/old-page" "/new-page";
}

server {
    if ($redirect_301) {
        return 301 $redirect_301$is_args$args;
    }
}

Loops and chains

A redirect whose target is itself redirected costs the visitor a second round trip, and two rules that point at each other never resolve. Point every old URL straight at its final destination. The generator rejects loops and chains instead of emitting them.

Choosing the status code

Use 301 or 308 for a permanent move, so search engines transfer ranking to the new URL. 308 and 307 keep the request method, which matters for POST requests; 301 and 302 let browsers turn a POST into a GET. Use a temporary code only if the old URL will come back.

Open the Redirect map generator

Frequently asked questions

Does a 301 redirect keep the query string?

Not automatically in every server. The generated Nginx rule appends the original query string, and Apache preserves it by default. With Caddy, add ?{query} to the target when you need it.

How long should I keep redirects in place?

At least a year, and longer for URLs that other sites link to. Search engines can take months to transfer a page's ranking, and old links keep arriving long after that.

Can I redirect a whole directory with this?

This generator matches exact paths only, on purpose, so a rule can never catch more than you listed. For a whole-prefix move, write a single regex rewrite by hand and test it carefully.

Guides