Wednesday, November 6, 2013

Create virtual hosts in a WAMP server

This simple example demonstrates how to get virtual hosts up and running quickly on your WAMP server.

The Windows Apache MySQL PHP (WAMP) server is incredibly powerful. Not only does it allow you to host a website using the world's most flexible web server, it also allows you to do so on your Windows host.

But don't think because you're on a Windows host that you lose much of the flexibility found on the Linux equivalent. In fact, much of the feature set translates -- this includes virtual hosts. Using virtual hosts allows you to, effectively, host more than one site on a single machine.
For example, say you want to host:
  • localhost
  • mysite.localhost
I'll show you how to easily do both with a single WAMP server (I assume the WAMP server is up and running, and you have administrative access to the files and folders on that machine). We'll focus on one configuration file at a time.


First, you need to edit your hosts file on the server. This will map the virtual host name to an IP address. To keep this simple, we'll map to mysite. Here's how:
  1. Open Notepad as the administrator.
  2. Open the file C:\Windows\system32\drivers\etc\hosts.
  3. Add the line: mysite.
  4. Save the host file (making sure to not save it as a .txt file).


The fastest way to access this file is to right-click the WAMP icon in the system tray and select Apache | httpd.conf (Figure A).
Figure A
The WAMP user menu
When you select the httpd.conf entry, Notepad will open with the contents of the httpd.conf file. Within this file, you need to uncomment out the entry for virtual hosts configuration file location. Search for these two lines:

# Virtual hosts
# Include conf/extra/httpd-vhosts.conf
Remove the "#" in the second line above and save and close the httpd.conf file.


The next file to edit cannot be accessed through the WAMP user interface; you should find this file in C:\wamp\bin\apache\Apache-XXX\conf\extra\ (XXX is the release number). Open that file in Notepad and add the following section (we're sticking with our current example of "mysite").

    DocumentRoot "c:\MYSITE"
    ServerName mysite.local
    ErrorLog "logs/mysite.log"
    CustomLog "logs/mysite-access.log" common
Notes about the code: You must add a directive for every virtual host you create. The site administrator is Also, if you need to serve the virtual host on a non-standard port, change it in the VirtualHost directive line. The reference to c:\MYSITE is the directory created to host the files and folders for the new virtual host; you'll need to create that folder (you can place it wherever you need in the folder hierarchy as long as it is accessible by Apache).

After you add the above code to the correct file, save it and restart your WAMP services. Now you should be able to see both localhost and mysite from your browser. You'll want to change those addresses to match your needs.