Virtual Hosts

The Apache web server allows for multiple domains to be run on a single server using virtual hosts. There are three types of virtual hosts, IP based (using multiple IP addresses), port based (using multiple port numbers) and name based (using DNS). This tutorial will focus on configuring name based virtual hosts with Apache on CentOS.

If Apache isn't already installed on your server, install it using yum.

yum install httpd

Create directory to store information for virtual host

The first step is to create a directory to install the data for your virtual hosts, this can be anywhere on the server but we will use /var/www/html/.

mkdir /var/www/html/ mkdir /var/www/html/

Set permissions

We will change the owner the directories from root to apache, this is a security measure.

chown -R apahce:apache /var/www/html/ chown -R apahce:apache /var/www/html/

We will change the permissons on the /var/www directory so that everyone has read and execute permissions.

chmod 775 /var/www

Create a webpage for each virtual host

Create a file called index.html in the directory for each virtual host.

vi /var/www/html/

An example of my index.html for testsite1 is below.

 <html>   <head>     <title></title>   </head>   <body>     <h1>This is a test website called</h1>   </body> </html> 

Do the same for testsite2.

Modify the Apache config file

The config file for Apache is located in /etc/httpd/conf/httpd.conf.

vi /etc/httpd/conf/httpd.conf

Uncomment the NameVirtualHost directive

NameVirtualHost *:80

Scroll down to the very end of the file, uncomment from to the end and configure the directives for your sites.

An example of my configuration is below.

 <VirtualHost *:80>     ServerAdmin     DocumentRoot /var/www/html/     ServerName     ErrorLog logs/     CustomLog logs/ common </VirtualHost>  <VirtualHost *:80>     ServerAdmin     DocumentRoot /var/www/html/     ServerName     ErrorLog logs/     CustomLog logs/ common </VirtualHost> 

Save and exit the file


Restart Apache

 service httpd restart

Test the virtual sites

If you own the domain names for the sites that you have created, just point the host record to the public IP address of your web server. In this example I have used and but I don't own these domain names. We can still test the site by amending local DNS in our test environment to point to the web server for these domains. This is done by editing /etc/hosts

vi /etc/hosts

Add in the IP address of your server, then the domain name. Mine is below, but yours may have a different domain name and IP address.

Then browse to the sites, to confirm that they are setup. You can use a web browser for this or a text based tool, I have used ‘curl'.

 [root@server1 ~]# curl <html>   <head>     <title></title>   </head>   <body>     <h1>This is a test website called</h1>   </body> </html>  root@server1 ~]# curl <html>   <head>     <title></title>   </head>   <body>     <h1>This is a test website called</h1>   </body> </html>