Name-based virtual hosting allows for hosting multiple websites with different domains and subdomains on a single server. To configure a web server for name-based virtual hosting, you will need to add a virtualhost configuration and for this example I am using Apache2. This tutorial was tested against Debian 6 Squeeze, but should be applicable for most linux operating systems. For this example we will use the nano as a command line editor, but you could use vi, gedit, or any other preferred editor. Also for the example, I will use sub.example.com as a placeholder, which will need to be modified to reflect the domain name or subdomain that you intend to use for your virtualhost. The domain chosen in the example is for a subdomain, but by simply dropping the prefix of “sub.” the virtualhost will instead then be valid for the primary domain of “example.com”.
We will need to create a virtualhost configuration for Apache, which is done by simply creating a file with the proper lines and enabling it once it is saved in the proper location. The default location for Apache2 on Debian based operating systems is /etc/apache2/ so the first thing we will need to do is to navigate to this folder.
From within the sites-available folder you can begin by creating a new file with a name that reflects the domain name or subdomain for which you’re virtualhost is intended.
This will open nano where you can then enter/copy the below configuration.
<VirtualHost *:80> ServerAdmin email@example.com ServerName sub.example.com ServerAlias sub.example.com DocumentRoot /srv/www/sub.example.com/public_html/ ErrorLog /srv/www/sub.example.com/logs/error.log CustomLog /srv/www/sub.example.com/logs/access.log combined </VirtualHost>
Once your virtualhost configuration file has been saved, we can enable it by entering:
$ sudo a2ensite sub.example.com
Once the site is enabled we can refresh Apache configuration by using the below command:
$ sudo /etc/init.d/apache2 reload
This will rescan and load any new configurations that have been added or modified for Apache; in our case it will load the new configuration for the virtualhost. Once the new Virtualhost has been configured and enabled, Apache will then recognize that it is hosting a new site called sub.example.com.
If you make modifications or add any additional virtualhost configurations you will need to repeat Step 6 for each time in order to update the configuration to reflect any new changes.