September 20, 2026

Nginx 404 Redirect Rules: return, rewrite, and error_page

A practical Nginx guide to handling old URLs with `return` and `rewrite`, while using `error_page` for real error handling instead of blindly redirecting every 404.

Nginx 404 Redirect Rules: return, rewrite, and error_page

Nginx can handle URL changes in several ways, but return, rewrite, and error_page solve different problems.

Use return for clear one-to-one redirects

When an old URL has a known new destination, return is often the simplest and most readable configuration.

Example:

location = /old-page {
    return 301 https://example.com/new-page;
}

Permanent moves typically use 301 or 308; temporary changes use 302 or 307 depending on the required behavior.

Use rewrite for patterns

rewrite is useful when many old URLs follow a predictable pattern. Regex rules can reduce repetitive configuration, but overly broad patterns can send unrelated requests to incorrect targets.

error_page is not a redirect database

error_page controls how Nginx handles error responses. It can render a custom 404 experience or route error handling internally, but a genuine missing URL should still be able to return an actual 404 status.

Avoid redirect chains

Prefer:

/old-a → /new-c

over:

/old-a → /old-b → /new-c

Direct redirects reduce extra requests and make maintenance easier.

Do not send every 404 to the homepage

Redirect only when the missing URL has a relevant new destination. Random bot paths or truly removed content do not become valid pages simply because they can be sent to /.

Use real traffic to decide what deserves a rule

Nginx access logs contain valuable information, but large sites may have enormous log volumes. no404 can add a product-focused layer that surfaces real 404 traffic and helps teams decide which old paths are worth mapping.

Conclusion

Use return for simple redirects, rewrite for pattern-based transformations, and error_page for error-response behavior. The core principle is to redirect moved content—not to hide every 404.

Related reading