301 Redirects for WordPress using the 404.php File

Redirection can be a tricky business in the world of SEO. If you’re launching a new website, migrating to a new domain or simply revising/improving the URL structure of your website you need to consider the importance of URL redirection.

I work on lots of post-migration audits and strategies to help businesses recover from failed migrations, so I know full well the devastating effects inadequate migration proceedures can have; like this…

Migration Traffic Loss

This is a real-world example of a website which suffered a -38% MoM loss of organic traffic and a -62% YoY loss following the launch of a new website, primarily due to inadequate migration procedures.

But this post isn’t about the pros and cons of redirection, so I’ll assume that everyone is aware of the general principles. If not – failure to redirect your old URL(s) to your new URL(s) can have devastating consequences and lead to a loss of organic ranking and a loss of search traffic!

Deploying 301 Rediects

There are many ways in which redirects can be deployed. These are often dependent on the type of web sever and the web platform that you’re using. Some of the most common methods include:

  • htaccess (Apache servers)
  • ISAPI (MS servers)
  • Plugins (for WordPress, Magento, Shopify etc)
  • Script-level redirection (i.e. through custom PHP, ASPX scripts – not JavaScript!)

WordPress is one of the most common web platforms and is the focus of this particular post.

Generally speaking, if you’re website is running on the WordPress environment and you want to deploy redirects you have two options:

  1. through a WordPress plugin such as EPS – https://wordpress.org/plugins/eps-301-redirects/
  2. through htaccess – assuming you have the knowledge

While these are perfectly acceptable solutions, there are potential overheads with each option.

Plugin Based Redirection

Using a plugin to handle your redirects and be a quick and pain-free experience. Many of the best redirect plugins for WordPress are free, quick to install/update, and often come with a number of key features such as bulk upload via a CSV to make the process of deploying redirects as quick and hassle-free as possible. Some even have built-in 404 detection to warn you when you should consider mapping additional redirects (some even do this automatically!).

So what’s the downside? Generally speaking the redirect information is stored in the associated database. in most cases, this will be the same database that powers the website, storing all page/post information, settings and everything in-between. In a very simplistic view, the more plugins you use the more it leads to database consumption and bloating. Funnily enough there are plugins such as WP Optimize that can help with that…but let’s not go down that road at the moment!

htaccess Based Redirection

Assuming your familiar with htaccess rules and regex, this can often provide a quick and easy way to deploy redirects. Redirects can be deployed one-by-one with relative ease, or regular expressions (regex) can often be used to match and map groups of redirects. However, htaccess can also be problematic, especially when working with a large number of redirects, and especially if there are no URL commonalities to match and map with regex.

The key point to note with htaccess files is that each htaccess rule is evaluated upon every single server request. Again I’ll assume a level of understanding here so I’m not going to delve into the finer details, but essentially when a request is made to the server for a web page, there are numerous requests running behind the scenes (i.e. each image, video, PDF, CSSfile, JavaScript file etc are all individual requests made to the server). This means that the htaccess file is processed upon each requests, therefore leading to performance overheads. That’s fine if your htaccess file contains a handful of redirection rules, but what if it contains lots? 1,000? 10,000? 100,000?! That’s a lot of processing upon each request, and most of the time it’s completely unnecessary.

I found myself in this predicament not long ago when mapping a large volume (250k+) URLs. Unfortunately there were no commonalities between old & new URLs so I was forced to use one-to-one mapping (yes it took forever, yes it was tedious, and no I never want to do it again!).

In this particular case the redirect were being deployed beneath a WordPress environment but I was reluctant to use either a plugin or htaccess to process the redirects. I was already aware of issues with server capability, so adding 250,000+ URLs via either of these methods would have had a notable impact.

I wanted a solution where the redirect was only ever processed at the point where it was applicable as opposed to being processed on every single request, so I started digging. I read various articles which detailed how to add actions to WordPress’ functions.php file to add custom PHP based functions to process the redirects, each of which was probably a valid solution to be fair, but seemed like overkill to me.

Modifying WordPress’ 404.php File for Redirect Handling

Not happy with the solutions I’d read on various blogs, I set about creating a PHP based solutions which adapts the default WordPress ‘404.php’ file with a bespoke function to capture the URL and process a redirect.

It script essentially capture the URL of the ‘not found’ page and processes an array of URLs to find a match. If the match exists, it processes a redirect to the associated new URL in the array, otherwise it just shows the standard WordPress ‘Not Found’ page. There’s no rocket-science involved here and I dare say , but for me this does exactly what it needs to do.

The great thing about this approach is that the logic to determine the redirection is only ever processed if a ‘404 Not Found’ error occurs first. So the processing of my 250K+ URLs only ever happens at the point where it’s necessary, not on every single request.

Disclaimer: I’m no Apache expert by any stretch of the imagination so I can’t comment on memory usage of htaccess vs database lookups vs php scripts with any accuracy. Likewise one could argue that the number of requests and server processing required to even reach the 404 page and process the redirection is no more efficient than processing a large htacces file! I just wanted to prove it could be done a different way, and more than happy to hear peoples thoughts on this.

Anyway, the code required is as follows:

Custom 404.php File for Redirect Handling via an PHP Array

"/new_path/newname.php",
		"/old_path/oldname.php"=>"/new_path/newname.php"

	 );

	//process redirect array
	if(array_key_exists($request,$arrMoved)){

		//contruct the redirect URI
		$newplace="https://".$_SERVER['HTTP_HOST'].$arrMoved[$request];
	    
		//process the redirect
		header("HTTP/1.0 301 Moved Permanently");
		header("Location: $newplace");
		header("Connection: close");
		exit();
	}
	else{
		//array match failed.
		//continue with the standard WP 404 error page here....
	    ?>

Please note that this code will probably need a little tweaking to work with your particular WordPress theme. For starters, you’ll need to fill the ‘else’ statement with the code for your ‘404.php’ file which is vary depending on your theme; but it will work 🙂

Until next time folks!

Leave a Reply

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