Wednesday, March 23, 2011

VirtualHost Examples1: Running several name-based web sites on a single IP address

This document attempts to answer the commonly-asked questions about setting up virtual hosts.

These scenarios are those involving multiple web sites running on a single server, via name-based or IP-based virtual hosts.

Your server has a single IP address, and multiple aliases (CNAMES) point to this machine in DNS. You want to run a web server for http://www.example1.com/ and http://www.example2.org/ on this machine.

#########################################################
Server configuration
# Ensure that Apache listens on port 80
Listen 80
# Listen for virtual host requests on all IP addresses
NameVirtualHost *:80
<VirtualHost *:80>
DocumentRoot /www/example1
ServerName http://www.example1.com/
# Other directives here
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /www/example2
ServerName http://www.example2.org/
# Other directives here
</VirtualHost>
##########################################################
The asterisks match all addresses, so the main server serves no requests. Due to the fact that http://www.example1.com/ is first in the configuration file, it has the highest priority and can be seen as the default or primary server. That means that if a request is received that does not match one of the specified ServerName directives, it will be served by this first VirtualHost.

Note: You can, if you wish, replace * with the actual IP address of the system. In that case, the argument to VirtualHost must match the argument to NameVirtualHost:
###############################
NameVirtualHost 172.20.30.40
<VirtualHost 172.20.30.40>
# etc ...
###############################
However, it is additionally useful to use * on systems where the IP address is not predictable - for example if you have a dynamic IP address with your ISP, and you are using some variety of dynamic DNS solution. Since * matches any IP address, this configuration would work without changes whenever your IP address changes.

The above configuration is what you will want to use in almost all name-based virtual hosting situations. The only thing that this configuration will not work for, in fact, is when you are serving different content based on differing IP addresses or ports

No comments:

Post a Comment