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.
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
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 -
So my file now looks like this.
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
Just edit your hosts file and match your virtual host domain to your localhost IP (127.0.0.1).
Edit Host File
Enable the virtual host site by typing in the following command -
Enable Virtual host
You will then be asked to restart apache -
Restart Apache Server
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.
Most Read Articles
Translate Our Site