Subdomains for localhost

A handy trick I just learned: you can use your hosts file to create subdomains of localhost.

For example, I have WordPress and Drupal both running on my machine for local web development testing. I used to access one at http://localhost/wp and the other at http://localhost/drupal. This works just fine, in general, but can lead to some awkwardness with things like .htaccess files and relative links when I move the site I’m developing to a real server.

By editing the hosts file, though, I can access my development sites at http://wp.localhost/ and http://drupal.localhost/, making it a little easier to test, migrate, etc.

In Windows (XP and Vista), you can find your hosts file in the C:\Windows\System32\drivers\etc directory. Add a couple of lines to the end of the file:

127.0.0.1       wp.localhost
127.0.0.1       drupal.localhost

And create virtual hosts in your Apache httpd.conf to point those domains to the correct directories. E.g.:

<VirtualHost *:80>
    DocumentRoot D:\xampp\htdocs\drupal
    ServerName drupal.localhost
</VirtualHost>

4 Responses to "Subdomains for localhost"

  1. are you sure that its working fine?, for me its not working after restarting the Apache!

    Yoosuf | 2009-05-27 01:12 | Permalink

  2. it’s not working for me too

    Toxic brain | 2009-06-26 03:30 | Permalink

  3. but
    how to create subdomain of subdomain on localhost
    like

    sajid.webspot.localhost,
    nasir.webspot.localhost,
    etc….

    Muhammad Sajid | 2009-11-19 02:31 | Permalink

  4. @Muhammad Sajid: You do that the same way. Just make a new entry in your hosts file and httpd.conf file for each new sub-sub-domain. Example:

    127.0.0.1       example1.wp.localhost
    127.0.0.1       example2.wp.localhost
    

    and

    <VirtualHost *:80>
        DocumentRoot D:\xampp\htdocs\wordpress1
        ServerName example1.wp.localhost
    </VirtualHost>
    <VirtualHost *:80>
        DocumentRoot D:\xampp\htdocs\wordpress2
        ServerName example2.wp.localhost
    </VirtualHost>

    Jonathan Brinley | 2009-11-19 08:56 | Permalink

Leave a Reply