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.

2 responses to “Automatically Create 301 Redirects for Migrations

  1. Hi David!
    First of all thanks for your awesome script. Unfortunately I have a client whos webhoster doesn’t allow me to access the .htaccess, nor create a new one in any folder of my wordpress installation.
    So I’m hoping for a clever plugin to get the job done. I found the wordpress plugin “Root Relative URLs” by Marcus Pope that does exactly that. In the plugins FAQ it mentions a feature to correct URLs that are already embedded in the site’s content and refers to your site for further information on this subject.
    So here I am kindly asking you if this functionality was already implemented in the current v1.8 (Jan 2013) of the plugin.

    1. Hi Lars,

      The plugin author was referring to our post on migrating a WordPress multisite. I think to replace the the relative URLs in your content you will only need to run a simple mysql query like this one on your posts table:


      UPDATE wp_posts SET post_content = REPLACE( post_content, 'href="http://yoursite.com/', 'href="/' );

      That should convert any internal links to relative links.

Leave a Reply to in4fun Cancel reply

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