Hosts
Apache Virtual Hosts provide an easy way to host multiple offline versions of your client sites while still accessing them through a simple, canonical URL. It breaks down like this:
- When you type a URL into your browser, the first thing it does is check a special file named HOSTS to see if it already knows where to direct the request
- If the URL isn’t listed, it runs off to the internet to find out where to send you
- BUT… if it is listed in the HOSTS file, the browser doesn’t bother finding out what to do from the internet; instead it goes straight to the IP address listed
- If the listed location is 127.0.0.1, the request is not sent to the internet, but instead goes straight to your local machine’s Apache install
So far so good – we open up the HOSTS file (on Windows XP you’ll find it at C:/WINDOWS/system32/drivers/etc/, on earlier versions of Windows it’s at C:/WINDOWS/), and add a new line at the end for the offline version of our client site:
127.0.0.1 myclientsite.local
So now all requests for the URL myclientsite.local will be directed to my own Apache server – but how does Apache know what to do with them?
Virtual Hosts
Apache has a special section of its configuration file that tells it what to do with requests for different domains. You’ll find the file, named ‘httpd.conf’, in the /conf folder under your installation of Apache. Some versions might have removed the relevant section to a separate file named ‘httpd-vhosts.conf’ – mine is under /conf/extra, but if you can’t find yours, just do a search for “httpd”.
Once you’ve located the correct file, look for a section containing the text “NameVirtualHost 127.0.0.1”. You might need to uncomment this line (remove the #); below it you can then add entries for each site you want to serve from Apache, in this format:
NameVirtualHost 127.0.0.1
<VirtualHost 127.0.0.1> ServerName localhost
DocumentRoot "C:Program Files\xampp\htdocs"
</VirtualHost>
This entry tells Apache that requests for “localhost” should be pointed to the folder listed under DocumentRoot (as you can tell, running XAMPP). For our client site, we simply add a new entry:
<VirtualHost 127.0.0.1> ServerName myclientsite.local
DocumentRoot "C:Program Files\xampp\htdocs\myclientsite\version2"
<Directory "C:Program Files\xampp\htdocs\myclientsite\version2"> AllowOverride All Allow from all
</Directory>
</VirtualHost>
And now all requests for http://myclientsite.local will be automagically routed to the specified folder, and your offline version of the client’s site can use all the features I mentioned above with no online/offline headaches (NB: if your Apache was running when you made the above change, you will have to stop and start it again before the change will take effect).
Note: the Directory tag might be necessary when the folder is not under the main localhost location.
To check virtual host configuration: from command prompt: /usr/local/apache/bin/httpd -S