Automatically Create 301 Redirects for Migrations


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 to

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:

"Redirect 301 /",
post_name, "/" )
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.