Thursday, June 9, 2011

How to serve several domains with one IP-address ?

The answer is ... use Apache's virtual host support. Apache was one of the first servers to support IP-based virtual hosts right out of the box. Versions 1.1 and later of Apache support both, IP-based and name-based virtual hosts (vhosts). The latter variant of virtual hosts is sometimes also called host-based or non-IP virtual hosts.
Name Based Virtual Hosts
Using Name Based Virtual Hosts is quite easy. The notable difference between IP-based and name-based virtual host configuration is the NameVirtualHost directive which specifies an IP address that should be used as a target for name-based virtual hosts.
For example, we use both www.akadia.ch and www.arkum.ch at the IP address 193.247.121.196. We simply add to one of the Apache configuration files (most likely httpd.conf) code similar to the following:
NameVirtualHost 193.247.121.196

<VirtualHost 193.247.121.196>
    ServerName www.akadia.ch
    DocumentRoot /www/akadia
</VirtualHost>

<VirtualHost 193.247.121.196>
    ServerName www.arkum.ch
    DocumentRoot /www/arkum
</VirtualHost>

Of course, any additional directives can (and should) be placed into the <VirtualHost> section. To make this work, all that is needed is to make sure that the names www.akadia.ch and www.arkum.ch are pointing to the IP address 193.247.121.196
When you specify an IP address in a NameVirtualHost directive then requests to that IP address will only ever be served by matching <VirtualHost>s. The "main server" will never be served from the specified IP address. If you start to use virtual hosts you should stop to use the "main server" as an independent server and rather use it as a place for configuration directives that are common for all your virtual hosts. In other words, you should add a <VirtualHost> section for every server (hostname) you want to maintain on your server.

No comments:

Post a Comment