How to redirect 404 to homepage in Nginx?

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 /;

Or

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 by AtulHost

Creator of AtulHost. An ardent Linux user. Comes from a business management background. Loves to do research on modern business insights and enterprise solutions like career, education, finance, investments ideas, marketing strategies, and productivity skills; technological trends like automation, artificial intelligence, cloud and edge computing, computer hardware and networking, data science, and the internet of things.

Join the discussion

Required fields are asterisked and email address will not be shared.

Ensure a friendly atmosphere to our members and visitors. Encourage the freedom of expression and exchange of information. Comments that are off-topic will be deleted.