How to redirect 404 to homepage in Nginx?

Published on


When a requested URL is not available or not found it’s advisable to redirect them to another URL or to a homepage that’s user-friendly. Nginx web server allows us to redirect off such 404 error pages to a custom URL, all we need to do is instruct Nginx’s site configuration to redirect such pages, and here is how to do that.

Redirect all the 404 to homepage.

To redirect all 404’s (or every page, whether invalid or not) to the homepage just open site’s config file and add the below directive in the server block. The default location of the config file is /etc/nginx/sites-enabled/default.

error_page 404 /;


error_page 404 /index.html;

Above directive instructs if error_page is 404 then redirect it to / “root”.

If the homepage URL of the site ends with index.html or any similar way just modify the root with that exact parameter to avoid any error.

But in the above way web server will show a clear 404 error, which is not good in the eye of search engines, better change the 404 status with 200.

All you need to instruct the directive to set the error status to 200.

error_page 404 =200 /;

Now we’re all done here, save the config and test the config if you want to.

Restart/reload the Nginx web server to apply those changes.

systemctl restart nginx

Now Nginx server will automatically redirect 404 URLs to their new location.

Published in: .

Leave a Reply

Your email address will not be published. Required fields are marked *