How to configure virtual hosts in Apache HTTP server
Source: Xmodulo
Virtual hosting refers to the technique that allows a physical server to host more than one website domain (e.g., site1.com, site2.com). Virtual hosting is prevalent in shared web hosting environments, where typically hundreds or more of websites or blogs are packed on a single dedicated server to amortize server maintenance cost.
You are not a web hosting company? Sure, virtual hosting can still be useful to you. For example, you can place multiple websites of yours on one VPS that you rent out, saving on your VPS cost. To serve multiple domains on a VPS, you just need to configure as many virtual hosts on its web server, and point the domains to the static IP address of your VPS.
Due to its usefulness, virtual hosting is supported by all modern web server software such as Apache, Nginx, Lighttpd, IIS. In this tutorial, I will demonstrate how to create and enable virtual hosts in Apache HTTP server under Linux environment. There is slight difference in the configuration between Debian-based and Red Hat-based systems. I will highlight the difference along the way.
Before I start, I assume that Apache HTTP server is already installed on your Linux server. If you haven’t, refer to our tutorials for Debian or Red Hat based systems, and install Apache server before proceeding.
As an exercise, let’s create a virtual host for domain abc.com on Apache web server.
Step One: Create Document Root Directory for Abc.com Domain
Start by creating a directory which will hold the web pages for abc.com. This directory is known as « document root » for the domain. Following the common practice, let’s organize all document root directories under /var/www
, and name them after the corresponding domains. Also, create a dedicated log directory for abc.com under /var/log
.
$ sudo mkdir /var/www/abc.com $ sudo mkdir /var/log/apache2/abc.com (Debian, Ubuntu, Mint) $ sudo mkdir /var/log/httpd/abc.com (Fedora, CentOS, RHEL)
Create a test webpage for the domain:
$ sudo vi /var/www/abc.com/index.html
<
html
>
<
head
>
<
title
>Welcome to Abc.com</
title
>
</
head
>
<
body
>
<
h1
>Sample page</
h1
>
This page is powered by Apache Virtual Host!
</
body
>
</
html
>
Change the ownership of the document root directory to the user that Apache web server runs as.
On Debian, Ubuntu or Linux:
$ sudo chown -R www-data:www-data /var/www/abc.com
On Fedora, CentOS or RHEL:
$ sudo chown -R apache:apache /var/www/abc.com