Last Updated: November 28, 2016
·
7.328K
· epocsquadron

A Catch-all Dynamic VirtualHosts for All Your Dev Sites

I like to keep all of the sites I'm working on in ~/Sites/, each in a folder named after the git repo they come from. I used to have a helper bash script which would allow me to append a new entry to my httpd-vhosts.conf file every time I added a new repository. Instead, we can set up a wildcard so we don't even have to do that.

With this file, typing foo.dev in your browser should give you the index inside /home/username/Sites/foo/public_html for example. Remember that you will still need to either set up a simple dns server like dnsmasq (wildcard dns + wildcard vhost! amazing!) or add each hostname to your hosts file in order to reach them.

# Catch all requests.
NameVirtualHost *

# Enable wildcard catching of domain 
#  names by vhost directive.
UseCanonicalName Off

<VirtualHost *>
    # Catch only requests to .dev domains.
    ServerName dev
    ServerAlias *.dev

    # Log everything so its sortable 
    #  by domain name.
    # LogLevel debug
    LogFormat "%V %h %t \"%r\" %s %b" vcommon
    CustomLog /$HOMEDIR/$USER/Sites/.log/access_log vcommon
    ErrorLog /$HOMEDIR/$USER/Sites/.log/error_log

    # Use the first part of the domain name
    #  as folder name to look in.
    VirtualDocumentRoot /$HOMEDIR/$USER/Sites/%1/public_html

    # Make php set the DOCUMENT_ROOT correctly
    #  since apache doesn't set it correctly to the 
    #  virtual one.
    #
    # See http://jbenner.net/blog/quick-tip-get-proper-document-root-when-using-mod-vhost-alias
    php_admin_value auto_prepend_file /$HOMEDIR/$USER/Sites/.conf/setdocroot.php

</VirtualHost>

Make sure modvhostalias is enabled in your apache installation (default on Mac's apache) and substitute $HOMEDIR and $USER with the approriate strings for your user and unix platform (e.g. /home/dan/ on linux and /Users/Dan/ on osx). The bit about php autoprependfile is explained in the link (along with the referenced file's contents), but is essentially just setting php's $_SERVER['DOCUMENT_ROOT'] correctly.

Extra:

You can add a second entry that catches ServerName/Alias .static that will work with sites that don't have anything above document root (e.g. VirtualDocumentRoot /$HOMEDIR/$USER/Sites/%1).