Development

Automatically Create 301 Redirects for Migrations

Development

In certain cases, when you migrate WordPress content from one site to another, you have to create 301 redirects.

I had a site recently where they wanted to split the blog off from the root domain and put it into a sub-folder of a multisites instance.  So we’d move the blog content (all the posts) from http://example.com to http://example.com/blogs/

After copying the posts (easily done with a WP export/import from one site to another) we needed to stop being able to view the posts on the old site and be redirected to the new one.

I didn’t feel like hand editing a load of 301s, so I created a quick bit of SQL to quickly output these:

select 
CONCAT(
"Redirect 301 /",
year(post_date),
"/",
lpad(month(post_date),2,'0'),
"/",
lpad(day(post_date),2,'0'),
"/",
post_name,
" http://example.com/blogs/",
post_name, "/" )
from 
wp_posts 
where 
post_status = "publish" and 
post_type   = "post";

This then creates an output that can easily be dropped into .htaccess – if you use something like MySQL Workbench you’ll need to output as CSV, remove the header row, and get rid of the quotes at the beginning and end of each row.

The example SQL above assumes a permalinks structure of /%year%/%monthnum%/%day%/%postname%/ and you’ll need to adjust it if you use a different structure.

Your next concern will now be the GUID – there are arguments for either changing it or leaving it as it is. I personally prefer changing it, but sometimes it’s more important not to confuse RSS readers and other feed harvesters.