Apache NameVirtualHost configuration using MAMP on Mac OS X

Summary: Here are some notes on how to configure a Name Virtual Host (NameVirtualHost) on an Apache web server. In particular, this is from the httpd.conf configuration file that I use with MAMP on one of my Mac OS X development systems.

In short, as I’m developing two different applications, one named "cato" and another named "zenf", these are the important name-based virtual host lines from my Apache configuration file:

NameVirtualHost *:8888

<VirtualHost *:8888>
  ServerName cato
  DocumentRoot /Applications/MAMP/htdocs/cato
  <Directory /Applications/MAMP/htdocs/cato>
    DirectoryIndex index.php
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

<VirtualHost *:8888>
  ServerName zenf
  DocumentRoot /Applications/MAMP/htdocs/zenf
  <Directory /Applications/MAMP/htdocs/zenf>
    DirectoryIndex index.php
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

If you’re not using PHP you can trim these entries down even more, as shown next:

NameVirtualHost *:8888

<VirtualHost *:8888>
  ServerName cato
  DocumentRoot /Applications/MAMP/htdocs/cato
</VirtualHost>

<VirtualHost *:8888>
  ServerName zenf
  DocumentRoot /Applications/MAMP/htdocs/zenf
</VirtualHost>

However, because I am currently developing PHP applications, I need those Directory entries.

Mac OS X /etc/hosts entries

Along with this configuration file, I have these corresponding entries in my Mac /etc/hosts file:

127.0.0.1   zenf cato localhost

That’s really all you need. With this setup I can access my two different web applications at these URLs:

http://cato:8888/
http://zenf:8888/

Apache NameVirtualHost problems

Looking back at my errors, my biggest mistakes in creating these Apache NameVirtualHost entries have been:

  • Forgetting the NameVirtualHost entry at the top.
  • Putting actual IP addresses in this file, like "127.0.0.1"
  • In a strange error, some part of MAMP/Apache doesn’t like it if you use a name like foo_bar; I just changed a test website name to foobar and it worked fine

If you're trying to configure an Apache NameVirtualHost on your system, if you'll just copy the second configuration entry I'm showing above and start with that, you should be fine. Just make sure you change the "8888" port to whatever port you're using on your system. For normal production servers, that should be port 80.