Virtual Hosts in Apache2 on Ubuntu 10.04
Setting up virtual hosts in apache2 on Ubuntu 10.04 allows a single server to hosts multiple websites. This generally requires four things:
- virtual host declarations
- enabling NameVirtualHosts
- creating DocumentRoots for each website to be hosted
- enabling each virtual host in Apache2
Virtual Host Declarations
Creating virtual hosts declarations can be done in the /etc/apache2/sites-available folder. Within the /etc/apache2/sites-available folder, a file named “default” provides a basic template with which virtual host declarations can be made.
Copy the default file to another file named after the virtual host it will serve.
- cp default [yourdomain.com]
The new file, [yourdomain.com], should be edited to look something like this:
<VirtualHost *:80> ServerName [www.yourdomain.com] DocumentRoot /var/www/[yourdomain] ServerAdmin [your email] ErrorLog /var/log/apache2/error.log CustomLog /var/log/apache2/access.log combined </VirtualHost>
Repeat the previous steps if more virtual hosts are needed.
Enabling NameVirtualHosts
Contained witihin the /etc/apache2/ports.conf file is a line that reads “NameVirtualHost *:80″. This line must be uncommented for virtual hosting to work correctly.
Creating DocumentRoots
Each virtual host must have a unique location to store all of the web docs associated with the virtual host. The default location created during the installation of Apache2 is /var/www. While DocumentRoots can exist anywhere in the server’s file system, it’s logical to keep everything in subfolders of /var/www. Thus, folders for each virtual host will be created within /var/www:
- mkdir /var/www/virthost1 /var/www/virthost2
The command above creates two folders within /var/www called “virthost1″ and “virthost2″ in which the web docs for each virtual host can be placed.
Enabling Virtual Hosts in Apache2
At this point, all that remains is to enable each virtual host within Apache2. The process of enabling the virtual hosts links the information located in /etc/apache2/sites-available to the /etc/apache2/sites-enabled folder. Generally, any edits to the virtual hosts must be done within the sites-available folder, which automatically updates the sites-enabled folder when Apache2 is reloaded. To enable virtual hosts:
- a2ensite [virtualhost 1]
- a2ensite [virtualhost 2]
Assuming the DNS settings for each virtual host are correct, entering either virtual host’s URL in the address bar of a web browser will display the correct website for each host.