After years of having to update both my apache vhosts and hosts files every time I needed to work on a new website or app, I decided it was to time to look into automating my dev environment setup.
My local setup
To start with I decided that I needed to have some consistency in the domains I use for development sites, so all future sites would be appended with .dev . For example, my local development domain for this site would be marclloyd.dev.
The first thing I needed to do was to make sure that all domains that ended with .dev would forward to my localhost. I achieved this by installing dnsmasq – Installation and setup was very easy :
Install dnsmasq with Homebrew
Update your homebrew installation:
brew install dnsmasq
Copy the default configuration file to /usr/local/etc/ :
cp $(brew list dnsmasq | grep /dnsmasq.conf.example$) /usr/local/etc/dnsmasq.conf
Copy the daemon configuration file to your LaunchDaemons folder:
sudo cp $(brew list dnsmasq | grep /homebrew.mxcl.dnsmasq.plist$) /Library/LaunchDaemons/
It’s also worth setting dnsmasq to start automatically:
sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist
Edit the dnsmasq conf file at /usr/local/etc/dnsmasq.conf and add:
We now need catch all domains with a .dev extension and forward them to localhost. Add the following line to the conf file:
Google chrome appears to have an issue where it overloads the DNS and hangs whilst loading sites. To get past this you’ll need increase the dnsmasq cache size in the config file:
Now restart dnsmasq:
sudo launchctl stop homebrew.mxcl.dnsmasq sudo launchctl start homebrew.mxcl.dnsmasq
Setting up our dynamic Virtual Hosts file
Now we have all domains ending with .dev forwarding to our localhost, we need to setup out dynamic Virtual Hosts file so that the url will be forwarded to the correct folder in our root directory. We do this by adding the following to out vhosts file:
<Virtualhost *:80> VirtualDocumentRoot "/Library/WebServer/Projects/%1" ServerName vhosts.dev ServerAlias *.dev UseCanonicalName Off <Directory "/Library/WebServer/Projects/*"> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny Allow from all </Directory> </Virtualhost>
This will forward all requests to the folder who’s name matches the first part of the domain in our root directory e.g marclloyd.dev will forward to a folder called marclloyd or mynewsite.dev will forward to a folder called mynewsite etc.
It’s then just a case of creating a folder in your root directory e.g. ‘mynewsite’ which you can access at http://mynewsite.dev – No more setting up vhosts and hosts files for every new site you work on locally.
This can of course be modified to work with any domain extension