Enable Virtual Hosting in Apache Web Server

Apache is widely used web server. This web server is called as “apache” in debian(Ubuntu..etc) world and in Red Hat world (Fedora, CentOS, RedHat..) called as “httpd”.

What is virtual host?

Virtual host is nothing but multiple domains are hosted in the same server. Depends on the domain name domain pages will be served. Called as “server blocks” in Nginx web server.

In this post will host domain test.com in Apache web server. First step create html directories for this domain.

sudo mkdir -p /var/www/test.com/html

Create another directory to store logs,

sudo mkdir -p /var/www/test.com/log

Assign ownership of the html directory with the $USER environmental variable,

sudo chown -R $USER:$USER /var/www/test.com/html

Also make sure that web root has default permissions,

sudo chmod -R 755 /var/www

Next create a index.html file using vi editor,

<html>
  <head>
    <title>Welcome to test.com</title>
  </head>
  <body>
    <h1>Virtual host is working!</h1>
  </body>
</html>

Then sites-available and sites-enabled directories needs to be created.
sites-available – Holds domain conf files
sites-enabled – Will hold symbolic links to virtual hosts conf file in sites-available directory.

sudo mkdir /etc/httpd/sites-available /etc/httpd/sites-enabled

Next you should tell apache to look conf files also in sites-enabled directory by editing http.conf file.

sudo vi /etc/httpd/conf/httpd.conf

Add this line at the end of the file,

IncludeOptional sites-enabled/*.conf

Then create conf file for domain,

sudo vi /etc/httpd/sites-available/test.com.conf
<VirtualHost *:80>
    ServerName www.test.com
    ServerAlias test.com
    DocumentRoot /var/www/test.com/html
    ErrorLog /var/www/test.com/error.log
    CustomLog /var/www/test.com/log/requests.log combined
</VirtualHost>

Finally symbolic link should be created to enable the virtual host,

sudo ln -s /etc/httpd/sites-available/test.com.conf /etc/httpd/sites-enabled/test.com.conf

Now restart the apache and domain will ready to be served.

Share your love
Nanthakumar
Nanthakumar

I’m a curious engineer, interested in various aspects of software engineering.

Articles: 7