Set up a name-based virtual host in Apache Web Server

Sometime you might want to host multiple sites on a single machine(i.e. it have only a single IP address) with different domain names.

Let says you intended to setup 2 totally new sites with the different domain names(i.e. www.domain1.com and www.domain2.com) in an existing Apapche web server.

There are only several simple steps of configuration are needed:

1) First step:

    # Ensure that Apache listens on port 80
    Listen 80

2) 2nd step:

    # Listen for virtual host requests on all IP addresses
    NameVirtualHost *:80

3) 3rd step:

    <VirtualHost *:80>
       DocumentRoot /www/document_root1
       ServerName www.domain1.com

       # Other directives here

    </VirtualHost>

    <VirtualHost *:80>
       DocumentRoot /www/document_root2
       ServerName www.domain2.com

       # Other directives here

    </VirtualHost>

Assumptions:

  • The document root for www.domain1.com is /www/document_root1.
  • The document root for www.domain2.com is /www/document_root2.
  • Both directories /www/document_root1 and /www/document_root2 are allowed to be accessed from the public.

Due to the fact that www.domain1.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.

January 16th, 2009 @ 04:25 PM • Filed under Apache