How to Redirect 404 to Homepage in NGINX

When a requested URL is not found, it is advisable to redirect 404 error to another URL with next steps. NGINX allows you to easily redirect 404 pages to a specific URL. Here’s how to redirect 404 to homepage in NGINX.

 

How to Redirect 404 to Homepage in NGINX

Here are the steps to redirect 404 to Homepage in NGINX. After you redirect 404 to homepage in NGINX, you may want to use a charting tool to monitor the key metrics about your website/application such as signups, traffic, sales, revenue, etc. using dashboards & charts, to ensure everything is working well.

 

1. Open NGINX config file

If you are using NGINX’s main configuration file nginx.conf, without virtual hosts, then run the following command

$ sudo vi /etc/nginx/nginx.conf

 

If you have configured virtual hosts for your website (e.g www.domain.com), such as /etc/nginx/sites-enabled/domain.conf then open it with the following command

$ sudo vi /etc/nginx/sites-enabled/domain.conf

 

Bonus Read : How To Disable NGINX Cache

 

2. Redirect 404 to Homepage in NGINX

NGINX provides a built-in directive called error_page that allows you to catch different error responses and process them further. To redirect 404 error code to specific URL (e.g /error.html), add the following line to your NGINX configuration file.

error_page 404 /error.html;

If you want to redirect 404 to homepage, add the following line

error_page 404 /

OR

error_page 404 /index.html;

In the above case, NGINX will redirect user to different URL, but with 404 response code. If you want to deliver a different response code (e.g 200), then you can modify the above directive as shown below

error_page 404 =200 /error.html;

Similarly, you can also catch 500 server error response,

error_page 500 /error.html;

 

Bonus Read : How To Implement NGINX Reverse Proxy

 

3. Check Syntax and Restart NGINX

Run the following command to check syntax of your updated config file.

$ sudo nginx -t

 

If there are no errors, run the following command to restart NGINX server.

$ sudo service nginx reload #debian/ubuntu
$ systemctl restart nginx #redhat/centos

 

That’s it! Now your NGINX server will automatically redirect 404 URLs to their new location.

By the way, if you want to create charts & dashboards to monitor your business or website, you can try Ubiq. We offer a 14-day free trial.

mm

About Ubiq

Ubiq is a powerful dashboard & reporting platform for small & medium businesses. Build dashboards, charts & reports for your business in minutes. Get insights from data quickly. Try it for free today!