This document is available on the Internet at:  http://urbanmainframe.com/folders/blog/20040521/folders/blog/20040521/

Apache Tricks: Pruning Virtual Hosts with 'Include'

Date:  21st May, 2004

Tags:

With twenty complicated virtual host configurations, the "httpd.conf" file on one of my servers was becoming unwieldy. Time for a little pruning...

flying the Apache flag

The "httpd.conf" file had grown to a massive 243Mb. Making changes to the configuration was proving to be an exercise in frustration. First I would download the file for editing, then I'd have to search through the 4000 lines of directives - jumping back and forth as necessary in order to effect copy-and-paste operations and so on. Finally, I would have to wait for the amended file to upload back to the server before I could restart. Doesn't sound too bad so far but, when I was experimenting with the configuration, or trying to get a rewrite rule to work correctly, I would have to go through the search-edit-upload procedure repeatedly and it became irritating after a while.

Each virtual host configuration was around 150 lines long. Thus, if I could remove them from "httpd.conf", I would have made considerable progress in making the configuration more manageable. Ideally, I wanted a single, small configuration file for each virtual host and I wanted them to be entirely seperated from the global directives in "httpd.conf".

Apache has an "Include" directive (in versions 1.3 and greater) which directs the server to include the directives in a seperate file at start-up. So I could do something like this in "httpd.conf":

Include /path/to/configuration/files/virtual_host1.conf
Include /path/to/configuration/files/virtual_host2.conf
...
Include /path/to/configuration/files/virtual_host20.conf

This would allow me to "spin-off" configuration files for each virtual host. Having twenty virtually-identical directives in my "httpd.conf" didn't really appeal to me, but it was the solution I was looking for, so I ran with it and it proved to be an effective way of managing the hosts. The best, however, was still to come.

I was reading up on the "Include" directive, for an unrelated configuration change, when I came across the following note:

New in Apache 1.3.13 is the feature that if Include points to a directory, rather than a file, Apache will read all files in that directory, and any subdirectory, and parse those as configuration files.

This constituted a eureka moment for me. I could replace twenty "Include" directives with just one!

Include /path/to/configuration/files

This is a simple, concise instruction and I love it. I no longer have to maintain a list of directives and I no longer have to edit two files when adding a new virtual host. I just upload a small configuration file into the appropriate directory on the web-server, restart the server and my new host comes online. Perfect.