In Nginx, the error_page directive can be used to define a URL for displaying specified errors.

Configuration Example

error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;

In this example, when a 404 error occurs, the /404.html page will be displayed. When 500, 502, 503, or 504 errors occur, the /50x.html page will be displayed.

Configuration Directives

Can be used in http, server, location, or if in location blocks.

Syntax: error_page code ... [=[response]] uri;
Default: Not configured

code is the HTTP status code. Multiple codes can be specified simultaneously:

error_page 404 /404.html;

# Multiple error codes, separated by spaces
error_page 500 502 503 504 /50x.html;

response is optional and used to change the HTTP status code of the response:

# Display /index.html for 404 errors and return status 200
error_page 404 =200 /index.html;

# 302 redirect to /redirect.html for 404 errors
error_page 404 =302 /redirect.html;

uri specifies the path to the error page:

# Can be a static file
error_page 404 /errors/404.html;

# Can be a dynamic page
error_page 500 /error.php;

# Named location (starting with @)
error_page 404 = @not_found;
error_page 502 = @fallback;
location @not_found {
    # Custom response
    add_header Content-Type application/json;
    return 404 '{"error": "Not Found", "code": 404}';
}
location @fallback {
    # Use proxy
    proxy_pass http://backend;
}

# Can be an external URL
error_page 403 http://example.com/forbidden;

# Full URI path
error_page 404 /custom/404/page.html;