How To Create Virtual Hosts On Apache Server To Host Multiple Websites
Table of Contents
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 a single server. The process is fairly simple and I will demonstrate it here itself. I am assuming you are running Ubuntu with the 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/html directory.
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. Example PHP Code
Step 4
Just edit your hosts file and match your virtual host domain to your localhost IP (127.0.0.1). Edit Host File
Step 5
Enable the virtual host site by typing in the following command –Enable Virtual hostYou will then be asked to restart apache –Restart Apache Server
Step 6
Test your website by visiting the domain name you specified.
Hurray! We have successfully created a virtual host on our apache server. If you ever get stuck at any step, feel free to drop a comment below.
LinuxAndUbuntu Newsletter
Join the newsletter to receive the latest updates in your inbox.