How To Redirect 404 to the Homepage in Nginx?

Published in

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 the Homepage.

To redirect all 404’s (or every page, whether invalid or not) to the homepage, just open the 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 /;

Or

error_page 404 /index.html;

The 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.

sudo systemctl restart nginx

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

Leave a Reply

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