Blog

Creating Virtual Hosts with Apache 2 on Mac OS X

Virtual hosting is a feature of Apache that allows you to associate a domain name with a directory on your web sever. This is very useful when developing a website because it more accurately reflects the environment your site will be in when deployed and it also allows you to reference images and other resources using root relative paths such as /images/myimage.png.

To create a virtual host with apache 2 running on Mac OS X 10.5 and later, you simply need to edit the 3 files files listed below. All of these files require root privileges to edit them. Use a command line editor, BBEdit, Smultron, or similar editor to modify these files. These editors allow you to enter a root password easily when saving the file.

  1. /etc/apache2/httpd.conf
  2. /etc/apache2/extra/httpd-vhosts.conf
  3. /etc/hosts

Enable Virtual Hosts in Apache 2

First you need to enable virtual hosts in apache by uncommenting a line in /etc/apache2/httpd.conf. You only need to do this once.

Open the file in your editor and scroll down until you find the lines shown below, it should be around line 465.

#Virtual hosts 
#Include /private/etc/apache2/extra/httpd-vhosts.conf

Uncomment the second line by deleting the pound sign (#) in front of it so it looks like this and save the file.

#Virtual hosts 
Include /private/etc/apache2/extra/httpd-vhosts.conf

Add a New Virtual Host Configuration

Next, you need to add a new virtual host configuration in /etc/apache2/extra/httpd-vhosts.conf. Append the following to the end of the file and edit to match your site.

<VirtualHost *:80>
    DocumentRoot "/Users/username/Sites/acousticwebdesign"
    ServerName acousticwebdesign.local
</VirtualHost>

DocumentRoot is the path to your websites’ root directory. ServerName is the domain you will use to access the site.

Add an Entry to /etc/hosts

Add the following to the end of etc/hosts. Replace acousticwebdesign.local with the domain you entered as ServerName in the last step.

  127.0.0.1 acousticwebdesign.local

Restart Apache to enable your new virtual hosts. Now when you visit http://acousticwebdesign.local you will be redirected to your local site.

It’s a bad idea to use the same domain as your live site, since any time you visit that domain on this computer, you will be redirected to your local site.

Questions, Complaints, Concerns? Leave a comment a below.

Comments are closed.