Virtual Hosts on Apache

This entry is intended to help you set up name based virtual hosts on the Apache Web server. Apache allows you to host several different domains and subdomains on a single IP. While this is an integral part of Apache, many people seem to struggle with setting up such a scenario. Hopefully this will help you learn from my mistakes!

We will assume you already have Apache installed and configured on your webby. Also, we will assume you are trying to host two sites; www.site1.com, which also hosts a blog on blog.site1.com, and www.site2.com

Adding Hosting Directories

By default, Apache serves files that are located in the hosting root folder, usually /var/www. You can put your site files just about anywhere, just make sure to be consistent and organized. For this article we will be creating the following directories for our first domain:

mkdir /var/www/www.site1.com
mkdir /var/www/www.site1.com/public
mkdir /var/www/www.site1.com/private
mkdir /var/www/www.site1.com/cgi-bin
mkdir /var/www/www.site1.com/logs

And so on… repeating the process for www.site1.com with blog.site1.com and www.site2.com. This gives you the directories to place your publically served files in public, files you do not want to expose in private, CGI scripts in cgi-bin, logfiles in logs. Configure Virtual Hosts

Next, we will add the configuration for each site to the default Apache configuration file found in /etc/apache2/apache2.conf

NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.site1.com
DocumentRoot /var/www/www.site1.com/public/

# Logfiles

ErrorLog /var/www/www.site1.com/logs/error.log
CustomLog /var/www/www.site1.com/logs/access.log combined
</VirtualHost>

Notice we added NameVirtualHost * to the beginning of the configuration. This is to enable multiple host support and only needs to be specified once in the config. Then repeat for your subdomain (blog.site1.com) and second domain (www.site2.com):

<VirtualHost *:80>
ServerName blog.site1.com
DocumentRoot /var/www/blog.site1.com/public/

# Logfiles

ErrorLog /var/www/blog.site1.com/logs/error.log
CustomLog /var/www/blog.site1.com/logs/access.log combined
</VirtualHost>

<VirtualHost *:80>
ServerName blog.site1.com
DocumentRoot /var/www/www.site2.com/public/

# Logfiles
ErrorLog /var/www/www.site2.com/logs/error.log
CustomLog /var/www/www.site2.com/logs/access.log combined
</VirtualHost>

This sets up two sites, which have their docements and logfiles contained beneath /var/www/nameofsite.com. You can adjust the paths if you wish to keep the files elsewhere. Now put some content in the public folders.

To finish off, just restart Apache:

/etc/init.d/apache2 restart

That’s it. Hopefully now you should be able to surf to your new sites through unique domain names. If you run into a problem don’t forget to add DNS zones for your new sites. Congratulations on setting up virtual hosts!