Monday, January 29, 2018

How To Create Virtual Hosts On Apache Server To Host Multiple Websites

If you have apache installed, you probably know what localhost is. Localhost allows a single website to be hosted locally.
However, when using virtual hosts, you can host multiple websites on
the single server. The process is fairly simple and I will demonstrate
it here itself.

I am assuming you are running Ubuntu with apache server.

Step 1

Move to the directory called /etc/apache2/sites-available

You will see a file called 000-default.conf, we need to copy that file to the same place with a change in the name.

I am creating a virtual host for sample.com so I will just copy and rename it to sample.com.conf using the following command -

Create a virtual host file

Step 2

​Now
we need to edit this file. I will be using gedit for this. You can see
that there are a lot of comments in this file. We need to get rid of all
the comments to make it more understandable.

So you can see in the image below I have removed the comments and this is what it looks like now.

​Now
we need to add 2 important configurations The ServerName and the
ServerAlias. The server name is the very basic domain that should match
your virtual host. The ServerAlias is another configuration that should
match the base domain. So both these configurations will be as follows -

ServerName & ServerAlias

Just
add both configs to the file and change the DocumentRoot to where you
would want the website to be stored. I am using a sub-folder called
sample in /var/www/htmldirectory.

So I will change my document root to this -

DocumentRoot /var/www/html/sample.

​​So my file now looks like this.

Step 3

​You need to now create an index file for your website. I have created my index.php file with the following code.