Virtualhosts are used to configure an URL or domain to be replied by our server, the virtualhost points the domain to a location in our server, then the server handles the response based on the files placed on that location. For example if in our location there is an index.php file, by default apache will load this file when visiting the domain configured in the virtualhost through the web browser. In this guide we'll be configuring a local virtualhost in ubuntu (though the process is similar for windows or mac), so it is not necessary to have bought a domain, however the same process could be used for configuring domains in a remote server (or a real domain) in apache.
Step 1 Set the location
We need the location where the source files are placed to write it on the virtualhost file, you can use an existing location or create a test location by typing the following commands that will create an index.php (whose content is the phpinfo function) inside a "test_site" folder located in the home directory (in linux).
cd mkdir test_site echo '<?php phpinfo();' > test_site/index.php
Step 2 set the virtualhost file
Create a file called "test_site.conf" in /etc/apache2/sites-available folder, then save it with these contents on it:
<VirtualHost *:80> DocumentRoot "/home/your_user/test_site" ServerName test-site.local ErrorLog /home/your_user/test_site/error.log <Directory "/home/your_user/test_site"> Order allow,deny Allow from all AllowOverride All Require all granted </Directory> </VirtualHost>
Then enable the host by typing the following command in the terminal:
sudo a2ensite test_site.conf
Step 3 edit host file (only for local virtualhost)
For this case we want our domain pointing to our server, with real domains this is done by configuring a DNS record, but that's another topic, in this case we are going to edit the host file to force a domain to resolve to our server ip.
To do so we need edit the host file, located in the /etc/ folder, add the following line at the bottom:
At the end it should look something like this, don't worry if it doesn't look entirely equal, host files tend to vary from one system to another.
Step 4 Test
Restart apache by typing in the terminal:
sudo /etc/init.d/apache2 restart
Then in the web browser go to http://test.local, it should load the index.php running the phpinfo() function.