A better way to organize localhost

June 12, 2011

I have a lot of projects going on, and I’m doing them all on my home computer, using a xampp server @ locaholst.

Since I have a lot of projects, the folder structure is like this:

c:\xampp\htdocs\project1 => http://localhost/project1
c:\xampp\htdocs\project2 => http://localhost/project2

The problem was that when the sites goes live, they are like:

http://localhost/project1 => http://project1.com
http://localhost/project2 => http://project2.com

This is messed up my code because the root folder changed. On localhost, the root folder is http://localhost/ and the projects are inside subfolders. My solution was for a long time to have a method named getRoot() that returned /projectX/ subfolder as root when localhost and / as root on live server. But I had to use this method every single time I make a link. This is not really a problem until you start making URLs pretty, and some other occasions.

Well, then, one bright and sunny day I though, why am I doing this? Shouldn’t there be an easier way? And of course there was – I just never really bothered to check.

Add lines into c:/windows/system32/drivers/etc/hosts file: project1.local project2.local

And then configure your local httpd.conf file, with adding the lines and restarting apache:
<VirtualHost *:80>
ServerName project1.local
DocumentRoot “c:/xampp/htdocs/project1”
DirectoryIndex index.php index.html index.html index.htm index.shtml
<VirtualHost *:80>
ServerName project2.local
DocumentRoot “c:/xampp/htdocs/project2”
DirectoryIndex index.php index.html index.html index.htm index.shtml

Now, when you want to test your site locally, you can use the addresses:

http://project1.local and http://project2.local

You don’t need to have your site inside c:/xampp/htdocs/ anymore either, by changing the VirtualHost configuration you can easily put them into c:/web/ or a folder of your choice.