How to create VirtualHost in Apache Web Server

In this tutorial we will learn how to create VirtualHost in Apache Webserver.
I believe you have already installed the apache web server in CentOS or Red Hat.(How to install apache web server)
With the help of VirtualHost we can host many domains or website from single Web Server.
This is a simple example to start with your first VirtualHost configuration in Apache Webserver.

I have used a few terms which is required for setting up the basic VirtualHost configuration.

DocumentRoot : This is used to define the Data path of website.In this example it is at /var/www/html/example.com. You can give other data path also
ServerAdmin : The contact person email id, Here I have given webadmin@example.com. You can also give root@localhost or your own email id. Customize as per your requirement
ServerName : Fully Qualified domain Name of server ,use hostname -f command to get FQDN of webserver. My server has FQDN as webserver.example.com

Optional:
DirectoryIndex : This is webserver main page or index page. It can be any with suffix index and applicable file format like index.html,index.php etc
ErrorLog As the name suggest it is for keeping log of web server.Here we have give the path /var/log/httpd/error_log which is already bydefault present there. You can customize this path as per your requirement
CustomLog: Here we have customize our webserver logging and all output will be log in file called /var/log/httpd/access_log . You can see common logformat has been used.
To know more about logformat ,read this link

Setup VirtualHost In Apache Web Server

This is an example of setting Virtual Host

Step 1: Change directory to /var/www/html

cd /var/www/html

Step 2: Create a directory called example.com

mkdir example.com

Step 3: Create index.html file inside example.com directory

vi example.com/index.html

Hello world

Step 4: Take backup of/etc/httpd/conf/httpd.conf file.

cp -p /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.orig

Step 5: Edit /etc/httpd/conf/httpd.conf and in last line write down the below given content



    ServerAdmin webadmin@example.com
    DocumentRoot /var/www/html/example.com
    ServerName webserver.example.com
    DirectoryIndex index.php
    ErrorLog /var/log/httpd/error_log
    CustomLog /var/log/httpd/access_log common

Step 6: Now restart the apache web service

/etc/init.d/httpd restart

Step 7: Now open the web browser and in address bar type http://ip-address-of-webserver

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.