A very handy feature Apache offers is the ability to easily create Virtual Hosts – psuedo-domains that function like the real deal. I have to admit, I spent a couple years in the world of localhost before figuring out what could be done with vhosts, and remember the pain of always having to append a BASE_URL constant to all my links since the leading slash that marks an absolute path [see Note 1] was unavailable – and having to update that constant every time a version changed. Not to mention have to explode and slice REQUEST_URI when dealing with pretty URLs, and having a chilly relationship with $_SERVER in general.

It’s basically a 2 step process:

1. Create a Virtual Host node in an apache configuration file [see Note 2]:
NameVirtualHost *:80
<VirtualHost *:80>
DocumentRoot "C:/Apache/htdocs/some-site"
ServerName whatever.youwant

2. Update your hosts file (on XP, Vista and Windows 7 it’s C:\Windows\system32\drivers\etc\hosts) to point to that ServerName:
[code] whatever.youwant

That’s it. From that point on (after restarting Apache, of course), if you type in “http://whatever.youwant” in your browser’s address bar, you’ll be see what would have been in http://localhost/some-site.

More details:

– The ServerName is arbitrary – you can really use anything you want here, as long as it conforms to the rules for valid URLs (although I’ve never experimented with multiple dots). Obviously, if you use a real domain here (google.com), you’ll won’t be able to access that site normally. I personally use “.local” as the TLD, but again it’s arbitrary.

– You can have as many virtual hosts as you want. If a ServerName is requested that doesn’t exist, you’ll be redirected to the first vhost in the list.

– The *:80 means “any IP on port 80” (and Apache should be listening to port 80). You can swap this with an IP if you’d rather.

– If http://.localhost fails after setting up a vhost, create a new vhost at the top of the list with the ServerName of “localhost” (or “local.host” or “my.stuff” or whatever you want).

– this directive can NOT be set with .htaccess files – Apache needs the vhost to determine where to look for the .htaccess file in the first place, so this fails before it starts, and simply cannot be done.


(1) For anyone that doesn’t know what I mean by the annotated statement – a path preceded by a slash becomes “absolute”, and indicates that the path should be interpreted from the document root (e.g., src=”/assets/js/script.js” on any page in your setup will be the same as http://your-site.tld/assets/js/script.js). I’ll admit it took me a really long time to figure that out, so don’t feel bad if you had to read this note =)

(2) This directive can be in any configuration file – httpd.conf works, although Apache recommends vhosts are placed in conf/extra/httpd-vhosts.conf, and that file is included in httpd.conf with this line:
[code]Include conf/extra/httpd-vhosts.conf[/code]