Serve Custom 404 Error Page Correctly in Nginx

22 August 2020

A soft 404 is a 404 page returned by a web server that has a 200 success HTTP code. When a 404 occurs, the 404 HTTP error status should be returned (of course).

In Nginx, this can be accomplished using the try_files directive. In the server block:

server {
    error_page 404 /404;
    location /404 {
        alias /path/to/www/;
        try_files /404.html =500;

In this example,

  • /path/to/www/ - the path to the directory with the custom 404 page.
  • try_files - instructs Nginx to try a series of files to use as the respone body. In this case we have a single 404.html page to try.
  • interenal - defines the the location /404 as internal. This prevents users from hitting https://<yourdomain>/404 directly.

Loading a non-existent page of this site: custom 404 page displayed, with HTTP 404 code returned from Nginx correctly. non-existent page of this site loaded in Chrome