This section is from the "Practical mod_perl" book, by Stas Bekman and Eric Cholet. Also available from Amazon: Practical mod_perl
In fact, you can create a complete configuration file in Perl. For example, instead of putting the following lines in httpd.conf:
NameVirtualHost 10.0.0.10
<VirtualHost 10.0.0.10>
ServerName tech.intranet
DocumentRoot /home/httpd/httpd_perl/docs/tech
ServerAdmin webmaster@tech.intranet
</VirtualHost>
<VirtualHost 10.0.0.10>
ServerName suit.intranet
DocumentRoot /home/httpd/httpd_perl/docs/suit
ServerAdmin webmaster@suit.intranet
</VirtualHost>You can write it in Perl:
use Socket;
use Sys::Hostname;
my $hostname = hostname( );
(my $domain = $hostname) =~ s/[^.]+\.//;
my $ip = inet_ntoa(scalar gethostbyname($hostname || 'localhost'));
my $doc_root = '/home/httpd/docs';
Apache->httpd_conf(qq{
NameVirtualHost $ip
<VirtualHost $ip>
ServerName tech.$domain
DocumentRoot $doc_root/tech
ServerAdmin webmaster\@tech.$domain
</VirtualHost>
<VirtualHost $ip>
ServerName suit.$domain
DocumentRoot $doc_root/suit
ServerAdmin webmaster\@suit.$domain
</VirtualHost>
});First, we prepare the data, such as deriving the domain name and IP address from the hostname. Next, we construct the configuration file in the "usual" way, but using the variables that were created on the fly. We can reuse this configuration file on many machines, and it will work anywhere without any need for adjustment.
Now consider that you have many more virtual hosts with a similar configuration. You have probably already guessed what we are going to do next:
use Socket;
use Sys::Hostname;
my $hostname = hostname( );
(my $domain = $hostname) =~ s/[^.]+\.//;
my $ip = inet_ntoa(scalar gethostbyname($hostname || 'localhost'));
my $doc_root = '/home/httpd/docs';
my @vhosts = qw(suit tech president);
Apache->httpd_conf("NameVirtualHost $ip");
for my $vh (@vhosts) {
Apache->httpd_conf(qq{
<VirtualHost $ip>
ServerName $vh.$domain
DocumentRoot $doc_root/$vh
ServerAdmin webmaster\@$vh.$domain
</VirtualHost>
});
}In the loop, we create new virtual hosts. If we need to create 100 hosts, it doesn't take a long time—just adjust the @vhosts array.
 
Continue to: