Easy Subdomain With Apache

Today no security post but a post on how to configure your apache server so you can easily add and remove subdomains. The reason I’m doing this post is because it took me a while to find the correct configuration and I don’t want you all to go through the same effort if I can just as easily share what I found (yay! free information!)

Ok here we go. What I wanted is the follwowing: I have a domain – lets say potatojuice.com – and I want my apache server to process requests for this domain. But! I also want to be able to setup subdomains easily without going into my VirtualHost config all the time. So, what I want is my web directory /var/www/potatojuice.com/ to contain all the possible subdomains. By default it alway’s contains the directory www. If I need a subdomain I easily create a new directory called ‘i-like’ and the subdomain i-like-potatojuice.com is redirected to load the content from /var/www/potatojuice.com/i-like

My virtual host looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<VirtualHost *:80>
    ServerAdmin admin@potatojuice.com
    ServerName potatojuice.com
    ServerAlias *.potatojuice.com
    DocumentRoot /var/www/potatojuice.com

    RewriteEngine on 
    Redirect permanent / http://www.potatojuice.com # Set the default subdomain 
    RewriteCond %{HTTP_HOST} ^([^\.]+)\.potatojuice\.com # URL needs to have a subdomain
    RewriteCond /var/www/potatojuice.com/%1 -d # Select content directory
    RewriteRule ^(.*) /%1/$1 [L] # Rewrite

    <Directory /var/www/potatojuice>
        AllowOverride all
        Order deny,allow
        Allow from all
        Options -MultiViews -Indexes FollowSymLinks
    </Directory>
    ErrorLog /var/log/apache2/error.log

    # Possible values include: debug, info, notice, warn, error, crit, alert, emerg.
    LogLevel warn

    CustomLog /var/log/apache2/access.log combined
</VirtualHost>

This allows you to just create a new directory in /var/www/potatojuice/. This subdir is from now on a subdomain on your website. Easy as that. Hope this is something you needed or where looking for.

Hugs, Ruben.

PS: I’m no sys admin so in case you see ‘misconfiguration’ or incorrect comments next to the rewrite rules please leave a message so I can update the post.

Comments