How to Create NGINX 404 Error Page


how to create nginx 404 error page

NGINX allows you to create custom 404 error pages that it serves in case a requested URL is not available. Here’s how to create NGINX 404 Error page for your website/web application.

 

How to Create NGINX 404 Error Page

Here are the steps to create NGINX 404 Error Page.

 

Before you proceed, please ensure you have installed NGINX in your Linux system.

 

1. Create Custom Error Page

First, create a custom error page that needs to be displayed in case of “404: Page Not Found” errors. You will need to create this file at /usr/share/nginx/html


$ sudo vim /usr/share/nginx/html/custom_404.html

 

Add the following code to it


<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 close the file.

 

2. Configure NGINX to use Error Page

Open the server block file in /etc/nginx/sites-enabled that you want to configure. In this example, we will use the default server block called “default”. You can change it as per your requirements.


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

 

3. Redirect 404 Errors to Custom 404 Page

We will use an error_page directive to direct 404 errors to your custom 404 error page that you created in step 1. We will create a location block for it so that root matches its file system location, and it is available only via internal redirects, and cannot be accessed directly by users. Open your nginx config file


$ vi /etc/nginx/nginx.conf

 

and add the following lines

 


server {
  listen 80 default_server;
  listen [::]:80 default_server ipv6only=on;

  . . .

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

 

4. Test Your Configuration

Test your NGINX configuration with the following command


$ sudo nginx -t

 

Restart NGINX to apply changes


$ sudo service nginx restart

 

Now open your browser and go to a non-existent page


http://your_server_ip_or_domain/non-existent-page

 

You will see the custom page that you setup earlier.

nginx 404 page

 

 

 

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!