I usually find it convenient to develop my websites and Web applications locally before pushing them to the production server. Mac OS X conveniently comes with the Apache Web server pre-installed. In fact, all you really need to do to start using it is to check the “Web Sharing” checkbox in System Preferences… > Sharing. You can then use your Web browser to navigate to http://localhost/, and you should see whatever files are in your Web root. The default Web root (root directory from which Apache serves files) is /Library/WebServer/Documents on Mac OS X. However, it’s useful, especially if you are working on more than one project at a time, to be able to host multiple sites on your Mac. To do this, you need to set up virtual hosts in Apache. Here is a step-by-step tutorial on setting up virtual hosts:
-
Open the file
/private/etc/hosts, and add one line for each virtual host you want like so:127.0.0.1 newhostname 127.0.0.1 othernewhostnameThe IP listed should always be
127.0.0.1, and the name of the host can obviously be whatever you choose. -
Open your Apache configuration file (
/private/etc/apache2/httpd.confon Mac OS X Leopard), and add these lines if not already present (you can add them at the end of the file):NameVirtualHost *:80 Include /private/etc/apache2/extra/httpd-vhosts.confThe
Includedirective tells Apache to look in a separate configuration file for virtual hosts, which makes it easier to manage. Make sure you use the path that corresponds to your installation of Apache. The path listed above corresponds to Leopard. -
Open the configuration file (you may have to create it, if it doesn’t exist already) that you pointed to in the main
httpd.conffile, and add the following for each new host name you specified inhostsabove:<VirtualHost *:80> ServerName newhostname DocumentRoot /path/to/root </VirtualHost> -
Restart Apache. The easiest way to do this on a Mac is to go to System Preferences… > Sharing and uncheck “Web Sharing”, then check it again. You should then be able to use your browser to navigate to
http://newhostname/.
This was just an overview. For more detailed information on setting up virtual hosts, see: Apache Virtual Host documentation.
A very easy way to manage virtual hosts on Mac OS X is through a handy application called VirtualHostX, which is free, except that it limits you to three hosts. You can register it for a small fee to remove this restriction.