Localhost shortcuts

apache

I have php and apache enabled and a folder test located in my ~/Sites. Is there anyway to access it thanks to the address http://test.dev instead of http://localhost/~user/test ?

Best Answer

This is called a "Virtual Host". Here's how I set them up:

  • Edit /private/etc/apache2/httpd.conf, and change

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

    to be:

    # Virtual hosts
    Include /private/etc/apache2/extra/httpd-vhosts.conf
    
  • Edit /private/etc/apache2/extra/httpd-vhosts.conf and add an entry that's something like this:

    <VirtualHost *:80>
        DocumentRoot "/Users/dave/Sites"
        ServerName test.dev
    </VirtualHost>
    
  • Edit /private/etc/hosts and add this entry:

    127.0.0.1 test.dev
    
  • Restart your webserver (I use sudo apachectl restart)

There are some example virtual host definitions in the httpd-vhost.conf file that are there to show you what the syntax looks like. They look like this:

# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot "/usr/docs/dummy-host.example.com"
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog "/private/var/log/apache2/dummy-host.example.com-error_log"
    CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common
</VirtualHost>

Add # signs to the beginning of those lines to comment them out.


An alternative to this is to use an app like VirtualHostX to do this for you ($35).


Edit 5 Dec 2011:

Here's a new blog post by the makers of Alfred on how they set this up:

http://preppeller.com/2011/12/04/setting-up-virtual-hosts-on-your-local-os-x-apache/