Setup Virtual Host in 0 sec

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/

        ServerAlias *
        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 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
$ 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 * 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: *

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:

Congratulations, you are all set up. Now you have a dynamic development environment and you can add new virtual hosts in no time.

You might like to read

Apache Cookbook

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s