Friday, March 9, 2012

Setting up dynamic sub domain via httpd.conf or htaccess

This post will teach you how to setup dynamic sub domain on your server.

We actually have 2 options on how to do it, maybe 3 which uses cpanel if allowed on your account.
Anyway, what I'll be discussing is the setup via httpd.conf or via .htaccess file.

To do this via httpd.conf, you only need to create a virtualhost with ServerAlias as below.
<VirtualHost>
    DocumentRoot /www/subdomain
    ServerName www.domain.tld
    ServerAlias *.domain.tld
</VirtualHost>


To do this via .htaccess, create the htaccess file on the www/ directory where your subdomains will be placed.

RewriteCond %{ENV:REDIRECT_SUBDOMAIN} =""
RewriteCond %{HTTP_HOST} ^([a-z0-9][-a-z0-9]+)\.domain\.com\.?(:80)?$ [NC]
RewriteCond %{DOCUMENT_ROOT}/%1 -d
RewriteRule ^(.*) %1/$1 [E=SUBDOMAIN:%1,L]
RewriteRule ^ - [E=SUBDOMAIN:%{ENV:REDIRECT_SUBDOMAIN},L]


Hope this helps. Thanks!