How to permanently redirect (301) all 404 (missing) pages in htaccess

After trying to find a solution for this and reading many blog posts, forums and trying different things I could not find a solution that worked and only using htaccess nothing else. Finally I found something that works using htaccess only using a combination of the information I found online. So if you want to 301 permanently redirect ALL your 404 pages to your homepage here is the htaccess code:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]

You need to make sure apache has ‘mod rewrite’ on and most web hosts do have this on by default otherwise you can ask your hosting provider if it’s not working. This code will redirect all missing pages to the homepage however if you want to redirect to another page instead just replace the slash / in the final line with your web page. 

If you only want to redirect specific pages that you know of then it’s pretty much just one line for each page in htaccess

Redirect 301 /blog/old-post-01/

However this wouldn’t work for me as I don’t know all the URLs of the site and wanted to capture all the missing ones, also if you have a large site you would have to put a lot of lines in your htaccess file. 

Other solutions I found said to put a line like this in htaccess:

ErrorDocument 404

This works but it is a 302 redirect not a 301 that I was looking for. A 301 is more valuable for Search Engine Optimisation. It’s telling Google and the other search engines that this is the new page and will always be that way, the old page no longer exists.

This article almost did what I needed but only useful in capturing broken links from specific domains coming to your site and redirecting them to the correct page.

<IfModule mod_rewrite.c>
 RewriteCond %{REQUEST_FILENAME} .*
 RewriteCond %{HTTP_REFERER} ^https?://([^.]+\.)?problem-domain\. [NC]
 RewriteRule (.*) http://redirected-domain.tld/target.html [R=301,L]
 # RewriteRule (.*) - [F,L]

Redirecting in WordPress

There were a lot of solutions for WordPress too using php by putting some code in the index.php because all pages pass through that file.

How to redirect 404 errors to the homepage?

And there is even the WordPress link juice plugin that will do it for you if you don’t want to mess around in the code to much.

Using PHP and Htaccess

Another solution that I didn’t try but ideally should work was to use a script and htaccess, using a php script in this case you would capture all 404’s in htaccess and direct them to your script and the script would 301 to the page you wanted.

htaccess file:

ErrorDocument 404 /permanent.php
redirect 301 /permanent.php

permanent.php file:

header(“HTTP/1.1 301 Moved Permanently”);

This would be useful if you didn’t have mod rewrite installed on your web host’s apache configuration.

So I hope I saved everyone a lot of time by posting a working solution only using htaccess to redirect all missing URLs on your site!