Name based virtual hosts with Apache web server

It may come as a surprise to some readers, given the ugliness of this site, but I am a web developer by trade. Since I've been using the Apache rewrite module to create nice URLs I've found I've been running into issues with resource paths.

So, for example, links to resources like "public/css/design.css" weren't being retrieved from my server correctly. I have to use "/public/css/design.css" instead (note the leading slash).

I have to use paths with a leading / on my live server(s), but locally that causes all sorts of headaches.

Step forward Apache named virtual hosting

With Apache NameVirtualHost directive and some tweaks to my hosts file I can fool the browser into fetching content for a domain from my local machine where I'm doing my development.

The NameVirtualHost directive in the Apache config allows me to tell Apache:
"all requests for this domain should get content from this directory".

Hosts file changes

Before we make changes to our Apache config to allow use of NameVirtualHost we need to tell the browser/OS that all requests for a particular domain should be sent back to itself (aka localhost).

To do that we need to add a line to the /etc/hosts file (this is in Linux world, Windows has a hosts file too, I'll add location of that later). You will need to be root (or administrator user in Windows land) to edit the hosts file.

In my hosts file I add an entry for a domain I want to work on locally:

127.0.0.1 www.dev.dafoot.co.uk

Which tells the computer "the apache server at 127.0.0.1 can serve content for the domain www.dev.dafoot.co.uk". As that IP address is a reference to localhost, all traffic to that domain is referred to the Apache instance running locally.

Apache Name based hosting config

Now we know traffic for a domain is going to be directed back to localhost we need to tell Apache how to handle the request. The following changes are made at the end of /etc/httpd/conf/httpd.conf

Tell the Apache http server to listen on given IP addresses:

Listen 192.168.2.101:80
Listen 127.0.0.1:80

We have assigned 2 IPs, one (127...) is for when we're using a browser on the same machine as the Apache instance and the other (192...) is the address that will be used by other machines on the LAN.

Next we add:
NameVirtualHost *:80

Now we are ready to add the domains we want to serve:

<VirtualHost *:80>
  DocumentRoot /var/www/html/dafoot
  ServerName www.dev.dafoot.co.uk
</VirtualHost>
<VirtualHost *:80>
  DocumentRoot /var/www/html/othersite
  ServerName www.dev.someothersite.co.uk
</VirtualHost>

Of course we then need to restart the httpd server.

Live and dev domains

You'll notice I have used www.dev..co.uk style addresses, this means I can still access the live version by leaving out that 'dev' part of the URL so I can view both at the same time which can prove very helpful!