Nginx 404 redirect tips and tricks

There are some very simple NGINX site configuration changes that can alter the way your site responds to requests for non-existent pages.

For example, you can redirect all requests that return a 404 to either a specific page, or your default index page. Just note that this can be very confusing when you’re troubleshooting a site and are constantly returned to your index page. You could be seeing proper requests, or false positives. The NGINX access logs will show a 200 status for all requests. This can be very crazy-making when you are trying to figure out why a URI isn’t rendering. Caveat emptor.

For reference, a typical simple try_files line looks like this:

        try_files $uri $uri/ =404;

To redirect all requests that don’t resolve to an actual page or asset, use the following try_files line in your location {} block, replacing the index.htm/html with whatever your home page or index file is:

location / {
        try_files $uri $uri/ /index.html /index.htm;
}

What’s going on here is that the ‘=404’, which is the final try_files fallback when all other try_files options have failed, is removed and replaced with a specific page.

If you want a custom 404 page instead, you can either replace the ‘=404’ with a specific file, such as:

location / {
        try_files $uri $uri/ /mycustom404.html;
}

Or, with a couple of extra lines, add in proper error handling:

location / {
        try_files $uri $uri/ =404;
        error_page 403 404 405 /mycustom404.html;
        error_page 500 501 502 503 504 /mycustom50x.html;
}

You can have as many (or as few) custom error pages as you need. You could set a single error page for all error conditions, or you could create a separate error page for each of the error codes.

Note: Remember to run service nginx restart (or the equivalent command for your chosen distro) as a user with sufficient privileges to enable any changes you make to your NGINX site configuration file.

Source: NGINX Pitfalls and Common Mistakes.

Leave a Reply

Your email address will not be published. Required fields are marked *