Thursday, January 29, 2009

A guide to virtual hosts in Apache

This is quick and dirty guide to using virtual hosts in Apache (on Windows). Included is an extra step on how to get a URL besides http://localhost/. There are several advantages to doing this, such as easier maintenance of various projects/apps etc.

1. Edit the httpd.conf file

In APACHE_PATH/conf/httpd.conf:
# Virtual hosts
Include conf/extra/httpd-vhosts.conf

Uncomment the line above.

2. Edit the httpd-vhosts.conf file

In APACHE_PATH/conf/extra/httpd-vhosts.conf

NameVirtualHost 127.0.0.2:80

Listen 127.0.0.2:80

<VirtualHost>

  ServerName subdomain1.local
  DocumentRoot "C:/wamp/apps/some_project/"
  DirectoryIndex index.php

  <Directory "C:/wamp/apps/some_project/">
    AllowOverride All
    Allow from All
  </Directory>

  #you can even have an alias here
  Alias /blog "C:/wamp/apps/some_project_blog/"
  <Directory "C:/wamp/apps/some_project_blog/">
    AllowOverride All
    Allow from All
  </Directory>

</VirtualHost>

Note:
The ServerName is configured in C:\windows\system32\drivers\etc\hosts (see step 3). If you do not plan to follow step 3, comment out the line with the ServerName directive.

3. Edit your
hosts file

(This isn't really necessary, but it doesn't hurt to have some cool top-level-domain redirection.)

In C:\windows\system32\drivers\etc\hosts (or wherever it is), add an additional line:
127.0.0.2 subdomain1.local

Note: you cannot specify a port number here. (this is not port mapping) E.g.: 127.0.0.2:8080 will not work.

4. "Debugging" purposes

You can do these in cmd:
ipconfig /flushdns
ipconfig /displaydns

The /displaydns command isn't necessary, but its useful for checking if you got your settings right.

5. Restart Apache

For more reading up, check out the friendly Apache docs.

No comments: