Automatic Subdomains – htaccess magic

Want to create subdomains on the fly?  Maybe you want member subdomains.  You don’t want to have to change your server config or edit files to create subdomains.  As long as you have wildcard subdomains enabled in your dns, you can use this .htaccess code to activate automatic subdomains.  All you have to do is create a directory with the name of the subdomain, but starting with a -.  For example, if you want sub.domain.com to be a subdomain, then create a directory named -sub in your document root.  That is all there is to it. You can create subdomains on the fly by having a script create the directory, or do it manually.

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/-
RewriteCond %{HTTP_HOST} ^([^\./]+)
RewriteCond %{DOCUMENT_ROOT}/-%1 -d
RewriteRule ^(.*)$ -%1/$1 [L]

There is one limitation with this approach.  You should not name any non-subdomain directory in your document root starting with – or it will operate as a subdomain.

Posted in Tips & Tricks