It's a very simple and very useful hack. This was done on Apache2 under Gutsy.
1. Add your subdomain(s) to your hosts file:
- Open up your network settings (System > Administration > Network)
- Click on the Hosts tab, select the localhost alias and click properties
- Add the subdomain(s) you want alongside localhost, separate with new lines
e.g:
localhost
extra.localhost
another.localhost
2. Apply subdomains to folders:
Open up a terminal or the Run Application diaogue (Alt+f2), then run the command:
gksudo gedit /etc/apache2/httpd.conf
For each subdomain you need to add a VirtualHost clause,
you also need to add one for the base localhost. The clause for each uses the template:
<VirtualHost *>
ServerName {Domain (e.g. localhost)}
DocumentRoot {Absolute path to folder for this domain (e.g. /var/www/)}
</VirtualHost>
Your file should end up looking something like this:
Code:
<VirtualHost *>
ServerName localhost
DocumentRoot /var/www/
</VirtualHost>
<VirtualHost *>
ServerName extra.localhost
DocumentRoot /var/www/extra/
</VirtualHost>
<VirtualHost *>
ServerName another.localhost
DocumentRoot /var/www/anothersite/
</VirtualHost>
Save and exit.
3. Restart apache:
Open up the terminal and run:
sudo /etc/init.d/apache2 restart
You should now be able to view your subdomains through whatever browser you use (but obviously only from your computer). All done!
Making use of it:
I write and test websites on my localhost before uploading them to my public sites and I don't want to go through my code renaming localhost to example.com every time I change something. Nor do I want to use relative URLs as they can get messy once you get folders involved. By putting each site I make on it's own local subdomain I can start all my URLs with a slash which means the URL starts at the base of the subdomain.
That's why I use it anyway.
-- Notes:
- I couldn't find a way to apply wildcards to the hosts file (e.g. *.localhost), does anyone know?
- There are ways to direct all subdomains to folders automatically (mod_rewrite is good for that) but that's less needed for this purpose and would require wildcards in the hosts file