Schoonology

The study of a Schoon

A Proper Migration: Conditionally Apply a 301 Redirect with WordPress

The Problem: Too many URLs

In the interest of coming back to writing on the side, I consolidated my static web page and blog into one site, schoonology.com. For the curious, this amounts to routing 3 second-level domains (one having two third-level domains) to this WordPress install. For your entertainment, feel free to click the following links. They should all route back to this article:

The Solution: The 301 redirect

Head on over to the Wikipedia article for more information, but there’s an HTTP status code for my exact problem: 301.

Almost everyone knows what a 404 means. It’s the HTTP status code for “that document does not exist”. If I left the other 3 domains hanging, that’s exactly where those links would lead: nowhere. So the first step was to go into my host’s settings and tell it to point all four to the WordPress install. Poof! No more 404′s.

Now, though, you’re left with four URLs that all point to the same place. To both normal users and (gasp!) search engines, it looks like there are four different websites that have the same exact content. Enter the 301. What it means is “this document has moved.” So both your browser and Google understand that they’ve gone to an old address, and can be re-routed accordingly. Ta da!

The Juicy Bit: How it’s done

I was delighted to discover with a bit of legwork on Google that WordPress comes with a redirect method build in. Not that I couldn’t just modify the headers myself in PHP; the wordpress method produced cleaner code. What I had discovered was wp_redirect.

After a few iterations, I wound up with the following code, added to my functions.php file:

function conditional_redirect()
		{
			if ($_SERVER["SERVER_NAME"] != 'schoonology.com')
			{
				wp_redirect('http://schoonology.com' . $_SERVER["REQUEST_URI"], 301);
			}
		}
		add_action('get_header', conditional_redirect);

First we define a function to do the redirect itself. Remember folks, composed methods and extracted methods are your friends, even when they’re not required for a function reference, as they are in this case. Inside, the conditional checks to see if we’re already where we want to be. If we are, then there’s no reason to redirect someone to it, is there? Otherwise, perform the redirect.

Be sure to specify the status code! WordPress defaults to 302, which means we’ve “temporarily” moved the document. This isn’t a temporary move, this is the document’s permanent new home. Finally, we call our method. Voila – All the links do what we want.

EDIT: After running with this code for a little while, the biggest problem I run into is not migrating this change into new themes. Be sure to do that…