Networking / Beginners

Defining Virtual Hosts

Virtual hosts allow a server to host multiple websites known by different hostnames. The Red Hat configuration has an entire section dedicated to virtual hosts, but it is all commented out. It is there only to serve as an example. To use virtual hosts, you must first uncomment the NameVirtualHost directive to enable name-based virtual hosts. There are IP-based virtual hosts, but those consume valuable IP addresses. Name-based virtual hosts are recommended by the Apache developers, and are preferred by most administrators.

On the sample Red Hat system, the NameVirtualHost directive is commented-out. The line is:

#NameVirtualHost *

The asterisk on this line stands for any address assigned to any interface on the host. To make this more understandable, we will be more explicit. We remove the hash mark (#) to activate the line, and set the NameVirtualHost address to the primary address of our server:

NameVirtualHost 172.16.5.1

Next, define the virtual hosts that will be served. For example, to host websites for fish.edu and mammals.com on the joe.example.org server, add the following lines to the httpd.conf file:

<VirtualHost www.fish.edu>
DocumentRoot /var/www/html/fish
ServerName www.fish.edu
</VirtualHost>
<VirtualHost www.mammals.com>
DocumentRoot /var/www/html/mammals
ServerName www.mammals.com
</VirtualHost>

Each VirtualHost directive defines a hostname alias to which the server responds. For this to be valid, DNS must define the alias with a CNAME record. The example requires CNAME records that assign wren.example.org the aliases of www.fish.edu and www.mammals.com. When wren receives a server request addressed to one of these aliases, it uses the configuration parameters defined here to override its normal settings. Therefore, when it gets a request for www.fish.edu, it uses www.fish.edu as its ServerName value instead of its own server name, and uses /var/www/ html/fish as the DocumentRoot.

These are simple examples. Any valid configuration directive can be placed within a VirtualHost container.

[Previous] [Contents] [Next]