Redirecting Subdirectory to Subdomain with htaccess

user1670009 picture user1670009 · Sep 14, 2012 · Viewed 24.6k times · Source

I'm relatively new to using .htaccess, and have never done any coding besides what I've read online. I'm using Bluehost, and I'd like to redirect my blog subdirectory to a subdomain. Example: I'd like to redirect www.example.com/blog to blog.example.com.

I already have code in place to always add www. to the beginning of my blog address in the root folder, but I don't know how to accomplish the above redirect by using code in .htaccess. Any help would be appreciated!

Answer

Oussama Jilal picture Oussama Jilal · Sep 14, 2012

A lot of web hosts today provide an easy implemention for subdomain creation in their administration panels. You just need to to go there, choose you subdomain name, and then point it to a directory in your tree.

If you can't, then it will be a little more complicated (You will need to resolve that subdomain to your server ip, configure some virtual hosts ... etc) and you may not have enough privileges to do that (unless you are on a dedicated server).

Edit 2

To redirect requests to www.example.com/blog to blog.example.com, try this :

RewriteEngine on

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

RewriteCond %{HTTP_HOST} ^blog\.example\.com$
RewriteCond %{REQUEST_URI} !^blog/
RewriteRule ^(.*)$ /blog/$1 [L,QSA]