How To Create and Use Custom Error Pages on Nginx Ubuntu 22.04

In this tutorial, we will learn how to make and use of custom error 404, 500 pages on nginx ubuntu 22.04.

How To Create and Use Custom Error Pages on Nginx Ubuntu 22.04

Use the following steps to make and use custom error pages on nginx ubuntu 22.04:

  • Step 1 – Create Custom Error 404, 500 Page
  • Step 2 – Configure Custom Error Pages in Nginx
  • Step 3 – Restart Nginx Server

Step 1 – Create Custom Error 404, 500 Page

Run the following command on terminal to make the HTML file for your custom 404 page:

sudo nano /usr/share/nginx/html/custom_404.html

Then add the following html code in custom error:

<h1 style='color:red'>Error 404: Not found :-(</h1>
<p>I have no idea where that file is, sorry. Are you sure you typed in the correct URL?</p>

Save and exit the file. If you’re using nano, hit CTRL+O to save then hit CTRL+X to exit.

Next, run the following command on terminal to make the HTML file for custom general 500-level error page:

sudo nano /usr/share/nginx/html/custom_50x.html

Then add the following html code in custom error:

<h1>Oops! Something went wrong...</h1>
<p>We seem to be having some technical difficulties. Hang tight.</p>

Step 2 – Configure Custom Error Pages in Nginx

Run the following command on terminal to open ngnix custom error page configuration file:

sudo nano /etc/nginx/sites-enabled/default

Use the error_page directive so that when a 404 error occurs (when a requested file is not found), the custom page you created is served

server {
    listen 80 default_server;


    . . .

    error_page 404 /custom_404.html;
    location = /custom_404.html {
        root /usr/share/nginx/html;
        internal;
    }
}

Thne, add the directives to make sure that when Nginx encounters 500-level errors (server-related problems), it will serve the other custom page made:

server {
    listen 80 default_server;


    . . .

    error_page 404 /custom_404.html;
    location = /custom_404.html {
        root /usr/share/nginx/html;
        internal;
    }

    error_page 500 502 503 504 /custom_50x.html;
    location = /custom_50x.html {
        root /usr/share/nginx/html;
        internal;
    }

    location /testing {
        fastcgi_pass unix:/does/not/exist;
    }
}

Step 3 – Restart Nginx Server

Run the following command on command line to restart nginx server:

sudo systemctl restart nginx

Conclusion

In this tutorial, i have shown to you how to make and use of custom error 404, 500 pages on nginx ubuntu 22.04.

More Tutorials

Leave a Comment