I do a lot of development work locally, running apache2, mysql, postgres, and any number of other things on my personal computer so that I can do my work. This offers me a lot of benefits: it’s faster, it doesn’t rely on an Internet connection, and it allows me to have complete control over my environment. There are some drawbacks to this though. Generally, you end up with many different projects and with each one comes a new directory, so after a while you have dozens of sites that look like
This by itself can cause some issues. First of all, now none of your files are running directly off of the document root which often causes some issues with badly written software. Secondly, it confuses the hell out of firefox’s password manager because it’s host based. It also looks kind of ugly having to put in all those different directory names. So wouldn’t it be nice if you could just write
Well, you can, and it’s not even difficult.
First of all, you’re going to need to make some changes to your apache/httpd/whatever config. You need to explicitly set
NameVirtualHost to your loopback address (which is almost guaranteed to be 127.0.0.1). You will also need to then set each
VirtualHost listing to this address as well:
NameVirtualHost 127.0.0.1 <VirtualHost 127.0.0.1> ... </VirtualHost>
Secondly, and unsurprisingly, you need to actually specify the subdomains you’re going to be using. If you’ve ever done this by hand before, you’ll know that this is also done with the
<VirtualHost 127.0.0.1> ServerName subdomain.localhost DocumentRoot /place/where/files/be/at/ </VirtualHost>
At this point, Apache or whatever webserver you’re using is configured to handle the subdomains. However, your computer itself is not. Sure, it knows that “localhost” maps to 127.0.0.1 but it doesn’t know where ‘subdomain.localhost’ is. You can fix this by editing your hosts file. This can be done via various graphical interfaces on some systems, or it can be found at “/etc/hosts” on most systems. Once you’re in there all you have to do is add:
If you’re paying attention, you’ll notice that a very similar line already exists in that file for “localhost”. In fact, you can map whatever you want in this file. Just remember that you’ll need to make an additional entry in both your webserver conf file and your hosts file for each subdomain that you want to use.