Rewriting SEO URLs When Moving WordPress to a Sub-Domain

If you have installed your WordPress blog to a sub-directory only later to determine you want to attach a sub domain to your site to point to your blog, you may find that all your SEO urls are now broken.  The fix to this problem is a simple Apache url rewrite that can redirect your users to the new article.

Your Ad Here

Here is the case that we find most often: You install your blog on your main domain inside a sub directory so that your urls look like ‘http://www.example.com/blog’  and wrote some articles such as ‘http://www.example.com/blog/2011/11/this-is-how-you-do-it/’.  All is fine and dandy until you decide that you want to have a separate sub domain for your blog and relocate the root to ‘http://blog.example.com’ and your article looks like: ‘http://blog.example.com/2011/11/this-is-how-you-do-it/’.  All is well except for the people that bookmarked the old url will get a 404 error response when trying to access that old bookmark or backlink that no longer points to the article.  With a quick change of your .htaccess file, you can make the old urls point to the new ones.  Use this line in your .htaccess file in the blog directory:

RewriteCond %{HTTP_HOST} !^blog\.example\.com$
RewriteRule ^(.*)$ http://blog.example.com/$1 [R=301,L]

The RewriteCond is the conditions that must be met to allow the RewriteRule to take place and checks to see if the current URL does not already have the blog sub domain.   If it does not (the ! preceeding it) then the Rule can take place, which is rewrite anything in the original request to the new blog sub domain address.  Note that this is put into the .htaccess in the blog sub-directory so the rewrite engine will remove that before matching the string in the rule.  It also sends a 301 redirect (R=301) and does not process further (L).  These can be changed as you see fit based on the Apache mod-rewrite documentation.

Respond to this post