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:
- #Enable mod_rewrite
- Options +FollowSymLinks
- RewriteEngine on
- # if requested subdomain is not "www"
- RewriteCond %{HTTP_HOST} !^(www\.)?example\.com [NC]
- # and we have not already rewritten this request to the subdomain's subfolder
- RewriteCond %{THE_REQUEST} !/folder/.
- # extract requested subdomain to %2
- RewriteCond %{HTTP_HOST} ^(www\.)?([^.]+)\.example\.com
- # rewrite the request to the subdomain's subfolder
- RewriteRule (.*) /folder/%2/$1 [L]
I hope this was helpful for all those seeking a similar solution.


Post new comment