This tutorial will show you how you can easily set up new virtual hosts on the stock Mac Apache install, perfect for testing and developing small PHP projects. Once you have done this, new projects can be set up by just creating new directories -- no adding hosts to /etc/hosts or adding new Apache configuration will be required.
We are going to use ~/Sites/ as the base directory, and we'll be able to dynamically serve from any directories under this. The name of the directory that you use will form part of the URL that you will use.
So, for example, if you created the following under ~/Sites/
mkdir -p ~/Sites/siteone/htdocs mkdir -p ~/Sites/sitetwo/htdocs mkdir -p ~/Sites/anothersite/htdocs
Then you will be able to access content from htdocs under the following URL's
Notice how we are using the .localhost TLD for this. RFC 2606 specifies that .localhost is reserved for local testing purposes.
So, how do we get to this setup? There are two parts:
1. Set up .localhost proxying
First of all, we need to make sure that any requests to a .localhost domain are routed to the local loopback device. For this, we will use the Automatic Proxy Configuration facilities of OS X.
We need to create the following Proxy Configuration File:
function FindProxyForURL(url, host)
{
if (dnsDomainIs(host, ".localhost")) {
return "PROXY localhost";
}
return "DIRECT";
}
Save the file as localhost.pac and place it in your ~/Sites/ directory.
Now, open up your System Preferences and go into Network. Select your network in the left hand pane, and click the 'Advanced...' button on right. Click the 'Proxies' tab and check 'Automatic Proxy Configuration'. In the 'Proxy Configuration File', enter the URL to your file, for example http://localhost/~username/localhost.pac.
Click on 'OK' and then 'Apply'.
2. Set up Apache VirtualHost
Edit the Apache configuration file for your user which is stored under /etc/apache2/users/, and add the following:
<VirtualHost *:80>
VirtualDocumentRoot "/Users/<username>/Sites/%1/htdocs"
ServerName subdomains.localhost
ServerAlias *.localhost
</VirtualHost>
Restart Apache with sudo apachectl restart
3. Test!
mkdir -p ~/Sites/mysite/htdocs echo 'Hello World!' > ~/Sites/mysite/htdocs/index.html
Visit http://mysite.localhost/ in your browser, and you should see "Hello World!"
Find this useful? You may be interested in my e-book, which is about creating the perfect PHP development environment on your Mac. Sign up to my mailing list to get more information:


