Best practise for Apache Virtual Hosts

 

As linux consultants we often work on systems that have been configured by someone else. Some of these systems have grown into webservers with a number of websites running as virtual hosts. Depending on the level of skill and insight the original system admin had, the apache configuration files can end up a tangled rats nest. I think this stems from the apache docs for vhost, albeit being very good, not give any guidelines on best practise for managing configuration files. Leading to people editing httpd.conf, to add virtual hosts, which soon gets mangled up. To make your virtual hosts manageable, the best practise is to use configuration files in /etc/httpd/conf.d/ for everything. Do not edit any of the config files in /etc/httpd/conf/ unless you really have to. A good starting point is to use a seperate file for each website. Or if you have specific needs create seperate configuration files to define difference web services. 

 

 

The advantages of doing this are numerous:

  • No risk of an apache software update overwriting your configuration
  • Easy to migrate website from one apache server to another, simply copy across the config file and document root.
  • Simple to intergrate with CMS (configuration management software), like puppet, as you do not need to edit the main httpd.conf
  • As with CMS intergration, if you want to build your configuration into some kind of OS package, such as .deb or .rpm, this is trivial with independent configuration files vs a mangled httpd.conf

An example configuration for a couple of different virtual hosts would look like this.

# ls /etc/httpd/conf.d/
site1.com.conf site2.com.conf virtual.conf

The virtual.conf files enables virtual host support.

# cat virtual.conf 
NameVirtualHost *:80

Each website is defined in its own configuration file site1.com.conf and site1.com.conf

# cat site1.com.conf

DocumentRoot /www/site1.com
ServerName site1.com
ServerAlias www.site1.com