Adding subdomains in Apache

Posted: 20th August 2009 by Tim in Apache, Ubuntu
Tags: , , , , , , , ,

There are a number of ways to add subdomains in apache, but here is the quickest and most basic way to get it done.

This example is for Ubuntu 8.04, but may be used on other flavours of linux if you find the correct paths to the files.

Let’s say you have a blog on example.com, and all files are stored in /var/www/blog. You would like to set up the subdomain blog.example.com. There are three steps to get this working.

First, we need to add an entry to the hosts file – this file basically tells your computer where to send network traffic. Open up /etc/hosts and add the following line to the bottom:

127.0.0.2 subdomain blog.localhost

Make sure that the address is unique (ie: there are no other 127.0.0.2 entries in the file. If there are, change the last number to something that isn’t being used). Note that on a live server you may need to use the server’s address.

Next, we need to tell apache that we’ve got a subdomain. Open up /etc/apache2/httpd.conf and add the following to the bottom of the file:

<VirtualHost 127.0.0.2>
DocumentRoot /var/www/blog
ServerName blog.example.com
</VirtualHost>

Again, use the address and subdomain name which you used in the hosts file.

And finally, restart the apache server:

sudo /etc/init.d/apache2 restart

You should now be able to load blog.example.com.