How to subdomains on Apache with mod_rewrite

Because I like to play with a lot of projects and code, I create subdomains for oprsteny.cz for almost every project. 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 I had to do was to create an *.oprsteny.cz wildcard record for my domain. This way, I don’t need to create a DNS record every time I need a new subdomain. When this is done, I checked for the record for example using dig, and I saw something like this:

$ dig *.oprsteny.cz
# .. skipping some output
;; ANSWER SECTION:
*.oprsteny.cz.          3600    IN      A       192.0.32.10

Once that’s done and it’s pointing to my server, I 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.

I was replacing the domain name, IP address and paths with my own, and I had a directory structure like this:

/var/www/oprsteny.cz/
/var/www/oprsteny.cz/www/
/var/www/oprsteny.cz/subdomains/
/var/www/oprsteny.cz/subdomains/<any subdomain>/

Apache vhost (stripped version):

<VirtualHost *:80>
        ServerName oprsteny.cz
        ServerAlias *.oprsteny.cz
        DocumentRoot "/var/www/oprsteny.cz"

        RewriteEngine on
        # Rewrite everything for oprsteny.cz to the
        # /www/ subdirectory
        RewriteCond %{HTTP_HOST} ^oprsteny\.com
        RewriteRule ^(.*) /www/$1 [L]

        # Rewrite all other *.oprsteny.cz subdomains
        # to their own directory
        RewriteCond %{HTTP_HOST} ^([^\.]+)\.oprsteny\.com
        RewriteCond /var/www/oprsteny.cz/subdomains/%1 -d
        RewriteRule ^(.*) /subdomains/%1/$1 [L]
</VirtualHost>

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

One thought on “How to subdomains on Apache with mod_rewrite

Leave a Reply