Apache Virtual Hosts

In Chapter 9, Automating Apache Virtual Hosts, we worked with Apache Virtual Hosts. This uses tagged data that defines the start and end of each virtual host. Even though we prefer to store each virtual host in its own file, they can be combined into a single file. Consider the following file that stores the possible virtual host definitions; this can be stored as the virtualhost.conf file, as shown:

<VirtualHost *:80> 
DocumentRoot /www/example 
ServerName www.example.org 
# Other directives here 
</VirtualHost> 
 
<VirtualHost *:80> 
DocumentRoot /www/theurbanpenguin 
ServerName www.theurbanpenguin.com 
# Other directives here 
</VirtualHost> 
 
<VirtualHost *:80> 
DocumentRoot /www/packt 
ServerName www.packtpub.com 
# Other directives here 
</VirtualHost> 

We have the three virtual hosts within a single file. Each record is separated by an empty line, meaning that we have two new line characters that logically separate each entry. We will explain this to AWK by setting the RS variable as follows: RS="\n\n". With this in place, we can then print the required virtual host record. This will be set in the BEGIN code block of the control file.

We will also need to dynamically search the command line for the desired host configuration. We build this into the control file. The control file should look similar to the following code:

BEGIN { RS="\n\n" ; } 
$0 ~ search { print } 

The BEGIN block sets the variable and then we move onto the range. The range is set so that the record ($0) matches (~) the search variable. We must set the variable when awk is executed. The following command demonstrates the command line execution where the control file and configuration file are located within our working directory:

$ awk -f vh.awk search=packt virtualhost.conf 

We can see this more clearly by looking at the command and the output that is produced in the following screenshot: