Moving wordpress from a subdirectory – and generation of 301 redirects from a google sitemap

So I mistakenly have installed wordpress in a subdirectory on my site – this worked well for testing, but I didn’t buy this domain to have my entire site sitting within a subdirectory!

WordPress has a good guide on this subject, which has step by step instructions on migrating your installation from one directory to another (including the root directory of your server):

The only problem is that once you do this, if you have indexed content in google (or links from other blogs) – you will now miss out on those links getting through to your site.   At this point you need to set up some redirects to your new site, which, if you have a large site, could be a real hassle if you’re manually adding 301 redirects to a .htaccess file.  Another way to do this is to use a pre-existing google sitemap file (sitemap.xml).  In this case I used a newly created one at the sites’ new location, outside of the ‘eric’ directory.  There was no difference in site links between moving the site outside of the ‘eric’ directory, so I can use this .xml without removing any nonexistent links.

I used a single line of not-so-elegant awk code from the bash command line to generate the required 301 redirects, so that any old links will now link to my non ‘eric’ directory links:

cat ../sitemap.xml | grep | awk -F”<loc>” ‘{print $2}’ | awk -F”</loc>” ‘{print $1}’ | awk -F”” ‘{print “Redirect 301 /eric”$2””$2}’

Obviously if you’re running this on your own system, you’ll have to edit ‘’ to be your domain, ‘/eric’ to be your current ‘old’ directory, and “../sitemap.xml” as the location of your sitemap. If you don’t have console access or don’t know awk, this probably doesn’t help you!

Here’s a snippet of the .xml file:


And here’s the resulting output:

Redirect 301 /eric
Redirect 301 /eric/
Redirect 301 /eric/linux-and-freebsd/yum-update-check-script-runs-via-crontab-and-emails-when-new-updates-are-available/
Redirect 301 /eric/recent-posts/

Paste this into a .htaccess file in the /eric/ directory, and presto, all the links now end up at the right place – google will be informed of this result, and will update their database accordingly, and anyone who used these links to link into this site will now go to the right place rather than a 404 or another error.

Leave a Reply

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