Apache Virtual hosts
- 3rd August 2005 | permanent link
- comments (0)
A very useful Apache Server feature are its Virtual hosts. I came across them when I got tired of developing sites localy and then rewriting half of the paths when the site was online. I was looking for a quick and easy solution and I found it. So instead of just one virtual host - localhost, you can have as many as your heart desires.
What are the benefits this approach has for a developer?
- No more localhost nonsense. From now on you do not have to write the whole url localhost/site_name/, only site_name.local (for instance).
- You act as if the site is online, so you can use the '/' to reference something in the root of the page. It turns out to be very handy on almost all sites ( when linking images for instance ). Think of it as an absolute path, but without the actual name of the site.
- All this means that when you publish the site it is only a matter of copying the site to an online server and you're all done.
So how is this done? First find the httpd.conf file in your Apache conf directory. Scroll down to the bottom of the file where you will find commented out an example of how to use the directive VirtualHost. Paste this after NameVirtualHost 127.0.0.1:
<VirtualHost 127.0.0.1>
DocumentRoot E:\WWW\hribar.info
ServerName hribar.local
</VirtualHost>
I pasted the actual lines I use on my local server. What we are doing here is telling the server that if a request for hribar.local comes in the root folder is E:\WWW\hribar.info instead of the default server document root. Because we have changed the httpd.conf file we must restart our server in order for the new setting to be recognized. Now, if you test the settings by opening your browser and typing in site_name.local you will see that it does not work. You will probably receive a page not found or a search will be made (depends on what plugins you have set in your browser). Why? You have to tell your operating system that the site name is an actual site on your local server and not online. To do this on Windows you must first find the file accordingly named hosts. In my case the file resides in C:\Windows\system32\drivers\etc. If you open the file you will see an entrie for localhost. All you need to do is add the line for your new virutal host so it looks something like this:
127.0.0.1 localhost
127.0.0.1 hribar.local
I tend to use the syntax site_name.local for the sole reason of easy swithing between the online and local site. All you need to do now is to close all of your browser windows for the new hosts file to be recognized. And that's all folks. Your very own Virtual Host is up and running.


No comment so far. Post whatever thoughts you might have regarding the current entry.