A subdomain for each directory with .htaccess and some mod_rewrite wizardry

June 10th, 2009

I don’t know how useful this will be to anyone, but I was playing around with my webserver a while back and because subdomains are pretty cool I thought I would figure out for myself how to do this.

You may use either httpd.conf or an .htaccess at your document root.

Make sure you have mod_rewrite turned on before you begin.
RewriteEngine On

First, use a RewriteCond like this to prevent redirection things like your favicon.ico that need to be available everywhere. Change this based on your setup.
RewriteCond %{REQUEST_URI} !^/(favicon.ico|images/.+|javascript/.*)$

Then, capture the subdomain in %1.
RewriteCond %{HTTP_HOST} ^(.+)\..+\..+$
This next line just prevents looping by making sure the REQUEST_URI doesn’t match the what’s in %1. Don’t ask how it works.
RewriteCond %1,%{REQUEST_URI} !(^[^,]+),/\1.*

This checks to see if what we have in %1 is in fact a directory under the document root.
RewriteCond /your/document/root/%1 -d

And finally, redirect ‘/anything’ to ‘/subdomain/anything’.
RewriteRule ^(.*)$ /%1/$1 [L]

And there we go, that should do it. All together, that’s:
RewriteCond %{REQUEST_URI} !^/(favicon.ico|images/.+|javascript/.*)$
RewriteCond %{HTTP_HOST} ^(.+)\..+\..+$
RewriteCond %1,%{REQUEST_URI} !(^[^,]+),/\1.*
RewriteCond /your/document/root/%1 -d
RewriteRule ^(.*)$ /%1/$1 [L]

Questions, comments, criticism, and other feedback are very welcome. If you have a better way of doing it, let me know!