.htaccess Redirect a Directory to a Subdomain and Force WWW


There's nothing like the smell of .htaccess in the morning.

Had to do a quick blog relocation for a friend the other day. The blog used to live at http://www.example.com/blog/ which we moved to the sub domain http://blog.example.com.

Search Engine Friendly

Did I mention, this is using a 301 redirect, which means the spiders will follow it and know, "oh this is where I should look for this file form now on."


It's really easy to set up that redirect in the .htaccess file in the root of example.com, meaning you can completely get rid of the /blog/ directory, which is great cause cluttered folders don't make anyone happy.

While we were in there we added a few lines to force the www to the rest of the domain. This helps ensure you don't get scolded by Google (via page rank) for having duplicate content on example.com/whatever-page.html and www.example.com/whatever-page.html

.htaccess

Options -Indexes +FollowSymLinks

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com$1 [L,R=301]

RedirectMatch 301 ^/blog/(.*)$ http://blog.example.com/$1

Geez, I love it when things work quickly and easily!


This works with any blog, or heck even forums: Wordpress, Movable Type, Expression Engine, Geek Log, Simple Machines Forums, vBulletin...you name it! The reason is: because it doesn't care if you have a hand coded manually updated blog all the .htaccess file sees is that someone is trying to access www.example.com/blog/this-post/ and it redirects to blog.example.com/this-post/.

So get going, move stuff around...just for kicks ;)

Popularity: 33% [?]


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Thank you so much! You may have saved me a huge headache. While I work on my primary domain, I created a subdomain for my blog but had to use a fairly wonky 404 page in the meantime.

I'll give this a try. Thanks again.

Thanks, but i want to redirect from example.com to example.com/blog ,,,??!

@XL I'd give this a shot, I haven't tested it myself but I'm about 99% sure on it!

Options -Indexes +FollowSymLinks

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/blog$1 [L,R=301]

This will ensure (especially important if you are moving your entire blog) that example.com/2008/06/this-blog-name redirects to example.com/blog/2008/06/this-blog-name.