Tag Archive for 'vhost'

Easy subdomains with mod_rewrite

Because I like to play with a lot of projects and code, I create subdomains for felixdv.com almost every day. Instead of going through the hassle of creating a CNAME or A record for every subdomain, creating an Apache vhost file and enabling it and creating the necessary directory structure, I figured there’s an easier way to do so.

First thing to do is to create an *.example.com wildcard record for your domain. This way, you don’t need to create a DNS record every time you need a new subdomain. When this is done, check for the record for example using dig, and you should see something like this:

$ dig *.example.com
# .. skipping some output
*.example.com.          3600    IN      A

Once that’s done and it’s pointing to your server, we need to create an Apache vhost which handles the requests with mod_rewrite, which is a rules-based url rewriting module for apache, and can easily handle different subdomains and actions based on the subdomain.

We’re assuming you’re replacing the domain name, IP address and paths with your own, and you have a directory structure like this:

/var/www/example.com/subdomains/<any subdomain>/

Apache vhost (stripped version):

        ServerName example.com
        ServerAlias *.example.com
        DocumentRoot "/var/www/example.com"
        RewriteEngine on
        # Rewrite everything for example.com to the
        # subdomains/www/ subdirectory
        RewriteCond %{HTTP_HOST} ^example\.com
        RewriteRule ^(.*) /subdomains/www/$1 [L]
        # Rewrite all other example.com subdomains
        # to their own directory
        RewriteCond %{HTTP_HOST} ^([^\.]+)\.example\.com
        RewriteCond /var/www/example.com/subdomains/%1 -d
        RewriteRule ^(.*) /subdomains/%1/$1 [L]

This way, you can just create a directory like /var/www/example.com/subdomains/blog/ to make http://blog.example.com work. Easy like that!