How to create a custom error 404 page on Nginx

If you want to display a custom message to your visitors when they try to navigate to an url path that doesn't exist on your website, you need to create a custom error page that will be displayed only when the result is not found.

In this tutorial you will learn how to create a custom error page on Nginx, we are creating a custom error page for 404 errors.

Step 1 - Create the html error page

Simply create an error page using your favorite text editor and name it something like error-404.html, you can name it anything you want but I recommend naming the file based on the error code, if the error page is going to be for 404 errors then the file should contain 404 as file name. This is only to make your job easier if you want to create more error pages for other errors such as 403, 500, 502.

Once you create the file error-404.html you need to upload it to your root folder.

Step 2 - Open Nginx config file

Run the command below to open nginx configuration file, the following command will open the default configuration file for nginx.

sudo vi /etc/nginx/nginx.conf

Note: vim is the text editor that I'm using, you can use any text editor that you are familiar with, simply replace vi with nano and the config file will be edited with nano text editor.

Step 3 - Setup the error_page directive

The error_page directive allows us to configure the custom error 404 page, the error_page directive can be placed on any server block, for example we put the error page directive on the http block

http {
     error_page 404 /error-404.html;

Now when someone tries to access something that doesn't exist on your server, the server will return the page error-404.html as response.

You can use the same directive for other errors, all you have to do is to replace the 404 error code as shown on the block above with any other error code.

For example, for error code 403, the server block should look like this

http {
     error_page 403 /error-403.html;

Step 4 - Restart Nginx Server

Before you restart your server, you need to make sure the configuration file nginx.conf doesn't have any syntax issues, to do this simply run the command below

sudo nginx -t

If the syntax doesn't have errors, you should be good to proceed restarting your nginx server


sudo service nginx reload


systemctl restart nginx

That's it! Now your server/website should return your custom error page as response for 404 error or any other error page that you created.


By now you should know how to create a custom error page on Nginx.