How to set up a custom error page in nginx?

Published on Aug. 22, 2023, 12:19 p.m.

To set up a custom error page in nginx, you can use the error_page directive in your nginx configuration file. Here is an example for setting up a custom 404 error page:

error_page 404 /404.html;
location = /404.html {
    internal;
    # path to your custom 404 error page
    root /path/to/your/website/;
}

In this example, error_page 404 /404.html specifies that nginx should serve the custom 404 error page located at /404.html whenever a 404 error occurs. The location block that follows sets the root directory for the custom 404 error page.

You can customize this example for other types of errors too, such as 500, 403, etc. For example, to set up a custom 500 error page, you can use:

error_page 500 /500.html;
location = /500.html {
    internal;
    # path to your custom 500 error page
    root /path/to/your/website/;
}

Note that the internal directive in the location block ensures that the custom error page is not accessible by clients directly, and can only be returned by nginx as an internal redirect.

Tags: