The 404 error means the requested page doesn’t exist on the server. If you are getting multiple 404 errors on your WordPress site and you don’t have any specific page for 404. In this case, you can simply make 301 redirect all 404 requests to your website home page. To do this you don’t need to install the extra plugin on your site, A small PHP code will do this for you.
Redirect 404 Error Pages to Home
Got to your WordPress theme directory and edit 404.php file in your WordPress. Let’s add following small PHP script at top of the file. The first line in the script will make the redirection as 301 permanently.
1 2 3 4 5 | <?php header("HTTP/1.1 301 Moved Permanently"); header("Location: ".get_bloginfo('url')); exit(); ?> |
Also you can replace .get_bloginfo(‘url’) with your website domain name to avoid extra request to WordPress to get domain name and make redirection more faster like below.
1 2 3 4 5 | <?php header("HTTP/1.1 301 Moved Permanently"); header("Location: http://www.example.com"); exit(); ?> |
Finally, test the redirection in your browser window.
8 Comments
Does anyone know if the code works as well for multisite installations?
If so, does the 404 page bounce to the subdomain / subfolder / subsite or the main or root domain / folder / site?
Great post!
Thanks :)))))
Thank you so much for writing up a blog on this topic. Having a 404 pages causes a big problem in terms of ranking, traffic & sales. Specially for E-commerce website. We do have tried “Redirection” plugin and it works perfectly fine and easy to use. Once again thanks for sharing the blog..!!
Keep up the good work.
Thanks for sharing information about 404 error pages.
404 error comes when requested page not found on the web server. If you are getting multiple 404 errors on your WordPress site and you don’t have any specific page for 404. In this case, you can simply make 301 redirect all 404 requests to your website home page.
Its works for my blog, very simple script. Thank you so much!
Hey brother, well if you do by 404.php I think can send 2 HTTP header codes (404 with 301)
or with plugin is only 301 immediately: https://wordpress.org/plugins/404-to-homepage-littlebizzy/
There’s a smarter way would be to redirect to a similar post using a plugin such as WP 404 Auto Redirect to Similar Post. It will use the words in the 404 URL to match against already existing pages.
A must have!