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

14-Jul-2023

.

Admin

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

Hello Friends,

In this short tutorial we will cover how to create and use custom error pages on nginx ubuntu. This post will give you a simple example of how to configure nginx to use custom error pages on Ubuntu. We will look at an example of how to add a custom error page. it's a simple example of how to create a custom 404 error page in nginx.

In this tutorial, we will explore the process of creating and implementing custom error pages, specifically the 404 and 500 error pages, on the Nginx web server. By customizing these error pages, we can provide a more user-friendly and informative experience for visitors encountering errors on our website. We will focus on Nginx running on Ubuntu 22.04.

Step 1: Create Custom Error 404, 500 Page


Use the following command on the command line to create 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, execute the following command on the command line to create the HTML file for the 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

Now execute the following command to open the Nginx 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

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

sudo systemctl restart nginx

I hope it can help you...

#Ubuntu