Creating a new web application in a development environment looks always the same. Download source code, create a new virtual host and add an entry to the etc/host file. It doesn’t take a great amount of time for an experience Apache user but it’s boring.
With an aid of “VirtualDocumentRoot” It’s possible to create a dynamic virtual host just once and never do it again. To use the VirtualDocumentRoot vhost_alias module needs to be enabled.
$ sudo a2enmod vhost_alias $ sudo /etc/init.d/apache2 restart
Now we can create our dynamic vhost file.
$ sudo vim /etc/apache2/sites-available/local.dev
ServerName local.dev ServerAlias *.local.dev VirtualDocumentRoot /home/luke/projects/%1/public Options Indexes FollowSymLinks MultiViews AllowOverride All
%1 in the VirtualDocumentRoot path will be replaced by the subdomain name. For example, a request to http://foobar.local.dev resolves to “/home/luke/projects/foobar/public”. There are few other interesting features which can be found on the mod_vhost_alias official website.
Now we have to enable the new vhost.
$ sudo a2ensite local.dev $ sudo /etc/init.d/apache2 reload
If you work on a custom domain (and I’m sure in most cases you do) you need to “teach” your operating system how to resolve it. The straight forward answer is edit “etc/hosts” file but then you need to edit it for every new website. Host file doesn’t allow wildcards so *.local.dev won’t work.
The solution is very simple. Install a DNS proxy. If you are windows user I recommend you Acrylic DNS. After installation go to “All Programs -> Acrylic DNS proxy -> Config -> Edit Custom Host File”. This file works perfectly well with wildcards so you can add something like that:
192.168.110.128 *.local.dev
Now restart the server “All Programs -> Acrylic DNS proxy -> Config -> Restart Acrylic Server“. The last thing to do is to set your network preferences to use the DNS proxy. Go to “Control PanelNetwork and InternetNetwork Connections”, right click on the appropriate network interface and choose “properties”. Double click on “Internet Protocol Version 4 (TCP/IPv4)” and set your Prefered DNS server to: 127.0.0.1.
Congratulations, you are all set up. Now you have a dynamic development environment and you can add new virtual hosts in no time.