Apache name-based Virtual Hosts

For this demonstration, we will be working with the httpd.conf file from an Apache 2.4 HTTPD server taken from a CentOS 7.x host. To be perfectly honest, we are far more interested in the configuration file, as Red Hat or CentOS supply it, than the actual configuration changes that we will make. The file will be available for download from the code bundle of the chapter. Our purpose is to learn how we can extract data from the system-supplied file and create a template from it. We can apply this to Apache configuration files or any other text data file. It is the methodology we are looking at, not the actual result.

To have some understanding of what we are trying to do, we must first look at the /etc/httpd/conf/httpd.conf file, that is, CentOS, Red Hat Enterprise Linux, or Scientific Linux. The following screenshot shows the virtual host section of the file that we are interested in:

Looking at these lines, we can see that they are commented and this is all a part of a monolithic httpd.conf. While creating virtual hosts, we normally prefer separate configurations for each of our potential virtual hosts. We need to be able to extract this data from the main file and at the same time uncomment it. We can then save this uncommented data as a template.

Using this template, we will create new configuration files that represent different named hosts that we need to have running on one instance of Apache. This enables us to host sales.example.com and marketing.example.com on a single server. Both sales and marketing will have their own configuration and websites, independent from each other. Additionally, it will also be very easy to add additional sites that we need with the template we create. It becomes the task of the main web server to read the incoming HTTP header requests to the server and direct them to the correct site based on the domain name used.

Our first task then will be to extract the data present between the opening and closing VirtualHost tags, uncomment it, and save it to a template. This will only need to be done once and will not be a part of our main script to create the virtual hosts.