Auto mapping development sites in Apache

apache-logo-1

Setting up a new virtual host entry in the Apache config files each time I setup a new development site on my local machine is a pain. Here’s how I am automatically mapping the http://*.dev hostnames to /home/user/dev/*/public in my home directory.

I normally have the files to be served by the webserver in a directory called /public. This allows other files to be stored together and optionally committed to my git repositories, with clear separation between what should and should not be served on the web. I started this following the Ruby-on-Rails conversion, but I am typically using this Apache setup for sites using PHP or static HTML (not for Rails apps).

This example is for Ubuntu Linux (14.10).

Create a new file called dev.conf with the following content (e.g. sudo vim /etc/apache2/sites-available/dev.conf):

# Set up permissions for VirtualHosts in /home/user/dev
<Directory "/home/user/dev">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Require all granted
</Directory>

# Automatic VirtualHosts with .dev
# /home/user/dev/xxx/public can be accessed at http://xxx.dev
<VirtualHost *:80>
    ServerName dev
    ServerAlias *.dev
    VirtualDocumentRoot /home/user/dev/%-2+/public
</VirtualHost>

Change /home/user/dev/ to the location of the sites to be served. The /public can also be removed if the files to be served are in the directory root, instead of the /public sub-directory.

Enable the Vhost Alias module in Apache:

sudo a2enmod vhost_alias
sudo service apache2 restart

Enable the Apache dev site:

sudo a2ensite dev
sudo service apache2 reload

Additionally, I am Dnsmasq to map all the *.dev domains to my local IP address, as per Dnsmasq (no editing /etc/hosts).

Now test out that it’s working.

Other information

The commands a2enmod, a2dismod, a2ensite, and a2dissite enable and disable the sites and modules used by Apache by creating, or removing, the symbolic links between the files in the *-available and *-enabled directories under /etc/apache2/.

Alternative instructions

Here’s how to do something similar on Mac: Local Development Environment: Apache, PHP, and MySQL with Homebrew

If you enjoyed this post, consider leaving a comment or subscribing to the RSS feed.
This site uses cookies. Find out more about cookies.