NGINX Catch All Errors


nginx catch all errors

NGINX provides many useful features to handle different types of errors on your website/application. However, there is almost some error that slips through the cracks and shows on users web browser. So it is advisable to create a catch all error page to handle all unhandled errors. Let us take a look at how to configure NGINX catch all errors.

 

How to Configure NGINX Catch All Errors

Here are the steps to configure NGINX catch all errors for your website/application.

Let’s say your website’s root folder is located at /var/www/default/html. So create a /error/ folder in /var/www/default


$ sudo mkdir /var/www/default/error

 

1. Open NGINX config file

Open NGINX config file in a text editor. You will find NGINX config file at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

$ sudo vim /etc/nginx/nginx.conf

 

2. Configure Catch All Error Page in NGINX

Now add the following lines to your NGINX config file

error_page 403 /error/403.html;
error_page 404 /error/404.html;
error_page 405 /error/405.html;
error_page 500 501 502 503 504 /error/5xx.html;

location ^~ /error/ {
    internal;
    root /var/www/default;
}

The above code will handle all errors with 4xx and 5xx code, by redirecting them to /error folder. This will act as a catch all error handler for your website. Now place custom HTML pages 403.html, 404.html, 405..html and 5xx.html to be displayed in case of each error.These pages will be shown, depending on the error code thrown by your server.

Instead of maintaining multiple error pages, if you want to display the same page for all errors then use a single page (e.g error_page.html) and refer to it for all error codes as shown below

Now add the following lines to your NGINX config file


error_page 403 404 405 500 501 502 503 504 /error/error_page.html;

location ^~ /error/ {
    internal;
    root /var/www/default;
}

 

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

 

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!