How to Redirect the Root of a Sub Domain to a Subfolder with .htaccess and mod_rewrite

Apr 17 2010

Sometimes as a web developer, I get the oddest requests. I recently needed to redirect the root of a subdomain to a sub folder within that sub domain. So basically I wanted to send a request for subdomain.example.com to subdomain.example.com/subfolder. I was able to achieve this by using Apache mod_rewrite and .htaccess. You will need mod_rewrite enabled on your server and hopefully you are on a Linux / Unix paltform for this to work. At the root of my domain I created a .htaccess file with this code:

  1. #Enable mod_rewrite
  2. Options +FollowSymLinks
  3. RewriteEngine on
  4.  
  5. # if requested subdomain is not "www"
  6. RewriteCond %{HTTP_HOST} !^(www\.)?example\.com [NC]
  7. # and we have not already rewritten this request to the subdomain's subfolder
  8. RewriteCond %{THE_REQUEST} !/folder/.
  9. # extract requested subdomain to %2
  10. RewriteCond %{HTTP_HOST} ^(www\.)?([^.]+)\.example\.com
  11. # rewrite the request to the subdomain's subfolder
  12. RewriteRule (.*) /folder/%2/$1 [L]

I hope this was helpful for all those seeking a similar solution.


Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
8
d
n
8
a
a
Y
u
Enter the code without spaces.
To prevent automated spam submissions leave this field empty.