Add 301 Redirects to WordPress Before  Launching

Before launching a new WordPress site it’s your responsibility as a developer to ensure that the URL structure currently indexed by search engines is preserved for SEO value. 301 redirects will tell search engines that a page has been moved permanently. I use this handy function by Scott Nelle which been pulled and modified slightly from his Simple 301 Redirects plugin. It allows you to add 301 redirects to WordPress using PHP:


/**
*	301 Redirects for Website Launch
*/
function base_redirect_urls()
{
	$current_address = base_get_address();
	$userrequest = str_ireplace(get_option('home'),'', $current_address);
	$userrequest = rtrim($userrequest,'/');
	$redirects = array(
		'/news/index.html' => 'https://www.newwebsite.com/news/',
	);
	foreach ($redirects as $storedrequest => $destination) {
		// compare user request to each 301 stored in the db
		if(urldecode($userrequest) == rtrim($storedrequest,'/')) {
			header ('HTTP/1.1 301 Moved Permanently');
			header ('Location: ' . $destination);
			exit();
		} else { unset($redirects); }
	}
}
function base_get_address()
{
	$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
	return $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
add_action('init','base_redirect_urls');

Another method involves using the .htaccess file to setup redirects. I’ve experiences issues with this technique and query string, so I tend to use this PHP method instead. What methods do you use to preserve URL’s after a migration? Are they better than mine?

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.