Redirect all 404 pages to your WordPress home page

I’m occasionally asked to redirect every 404 error on a site to the home page. There are a couple of reasons why you might not want to do this (see below) but there are also valid cases where it could be the right move for your site. If you’ve decided it’s the right thing to do, here’s how to accomplish it easily in WordPress:

Edit or create 404.php in your theme directory. Replace all of the content inside with the following lines:

<php
wp_redirect(site_url(), 301);
exit();
?>

And that’s all there is to it!

Why shouldn’t you do that?

There are a couple of reasons that redirecting all 404 errors could be problematic.

First, search engines are said not to pass all of a page’s link equity to the redirected page unless the content is very similar. So redirecting pages that used to rank well to the home page won’t work as a sneaky way to boost your home page.

Probably more importantly, though, is the fact that it will be difficult to monitor which links are 404ing since they’ll all just end up on the home page. The usefulness of Google Webmaster Tools and other methods of monitoring 404 requests is not just in preventing future 404s. The real power is that it helps you identify what your users are looking for and where they’re failing to find it. Fixing all 404s in an automated way makes that more difficult.

Get Just The Path from a Request in PHP

It can be a little tricky to get just the path of a request in PHP. $_SERVER['REQUEST_URI'] includes the query string. $_SERVER['SCRIPT_NAME'] may return index.php instead of the request if you’re using a CMS like WordPress which rewrites URLs.

The most reliable method I’ve found for returning only the path without the query string uses PHP’s built in parse_url() function:

$path_only = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);