When we are working in multiple projects and in several folder then virtual host will greatly help in making our job easier and clean. Virtual hosts allow us to set up websites on our localhost accessible using full domain names instead of via localhost/site. It will keep our sites organized and also our URL will be shorter and neat.
For example, if our Xampp is installed in drive C:, then one of our site path may look like C:\Xampp\htdocs\projectsfolder\subfolder\index.php. If we need to access it then, our URL will look like http://localhost/projects/folder/subfolder/index.php. Would it be nice if we can shorten this URL to access the same project ?
How to do it then?
Go to the folder C:\xampp\apache\conf\extra and open file httpd-vhosts.conf in your favorite text editor.
Uncomment the following line to enable name based virtual host on your server’s port 80.
Then add the following code and save it.
<VirtualHost *:80> ServerAdmin email@example.com DocumentRoot C:\xampp\htdocs\projects\myproject ServerName localhost </VirtualHost>
Now go the folder C:\Windows\System32\drivers\etc and open hosts file. Remember, this file should be opened Administrator privilege otherwise we will not be allowed to edit and save it. At the bottom of the page add the following code and save it.
Finally we need to restart the Apache server then we can nagivate our project with URL http://myproject.localhost/
Take another example where we are going to setup two projects. It will be similar for other multiple projects. We have two projects named firstproject and secondproject and their path is C:\xampp\htdocs\firstproject and C:\xampp\htdocs\secondproject. Then in configuration file you will need to add like this.
<VirtualHost *:80> ServerAdmin firstname.lastname@example.org DocumentRoot C:\xampp\htdocs\firstproject ServerName first.localhost </VirtualHost> <VirtualHost *:80> ServerAdmin email@example.com DocumentRoot C:\xampp\htdocs\secondproject ServerName second.localhost </VirtualHost>
And in the host file add the following lines
127.0.0.1 first.localhost 127.0.0.1 second.localhost
Now you can access first project with URL http://first.localhost/ and for second project will be http://second.localhost/.
To make work for remaining projects in your folder, you need to set it to default. Following code should be added in the configuration file before the above code.
<VirtualHost *:80> DocumentRoot "C:/xampp/htdocs" ServerName localhost </VirtualHost>