Accessing virtual hosts across a LAN

Like many web developers, I have a local Apache/MySQL/PHP setup for developing sites. To ensure maximum compatibility with live servers, I set up a virtual host for each site. That way I know all paths will work. For example, on my MacBook, all my sites live in subdirectories of /Users/myusername/Sites. It’s easy enough to set up a virtual host for each site; in Apache’s config file (normally httpd-vhosts.conf, but your set up may vary) I have the line:
NameVirtualHost *:80

and then a virtual host section for each site, for example:

<virtualhost *:80>
DocumentRoot /Users/myusername/Sites/site1
ServerName site1
</virtualhost *:80>

That sets up the Apache side of things. In order for my computer to know what address to map the site names to, I now need to edit my hosts file. On the Mac it’s in /etc/hosts; on Windows it’s more deeply buried in C:\Windows\System32\drivers\etc. In both cases you need administrator privileges to edit it. Easy enough on the Mac; in Windows you’ll need to run Notepad or another text editor of your choice as administrator (right-click on it in the Start menu as choose “run as administrator”).

For each virtual host that I set up in the Apache config file, I add a line to my hosts file:
127.0.0.1 site1
and that provides the mapping I need so that I can use my browser to go to http://site1 and Apache will serve up the correct site. The address 127.0.0.1 always maps to the local computer (i.e. localhost). But what if I want to access site1 from another computer on the LAN? How will it know where site1 is? That turns out to be easy-peasy.

First, find out the IP address of the computer hosting site1. For example 192.168.1.10. On the second computer, edit the hosts file. Add the line:
192.168.1.10 site1
Et voilà! Now, when I enter http://site1 on the second computer, it will find it on the first computer, even if it’s not the default served up by Apache.

Note, you may hit snags with this system if you use DHCP on your LAN, because the IP addresses of the host computers may change from time to time (e.g. if you reboot them). I recommend using static IPs on your local network for this reason, at least for those computers you are using to host websites.

This entry was posted in Web development and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>