This script is in use for many years now and does a decent job. I set up a MySQL table which specifies the basic configuration options for an Apache2 virtual host:

CREATE TABLE `vhosts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `DocumentRoot` text NOT NULL,
  `ServerName` varchar(255) NOT NULL DEFAULT '',
  `ServerAlias` varchar(255) NOT NULL DEFAULT '',
  `ScriptAlias` text NOT NULL,
  `CustomLog` text NOT NULL,
  PRIMARY KEY  (`id`)
) ;

In /etc/apache2/conf.d/vhosts.perl.conf I’ve put this little script:

<Perl>
use DBI;
use File::Path;
 
my $dbh = DBI->connect( "DBI:mysql:vhosts", "apache", "password" );
my $sth = $dbh->prepare("select * from vhosts");
$sth->execute();
while ( my $vhost = $sth->fetchrow_hashref() ) {
    unless ( -d ( split( / /, $vhost->{ScriptAlias} ) )[1] ) {
        mkpath( ( split( / /, $vhost->{ScriptAlias} ) )[1] );
    }
    unless ( -d $vhost->{DocumentRoot} ) {
        mkpath( $vhost->{DocumentRoot} );
    }
    unless ( -e ( split( / /, $vhost->{CustomLog} ) )[0] ) {
        my $dir = $vhost->{CustomLog};
        $dir =~ s/(.*)\/.*?$/$1/;
        mkpath($dir);
    }
    undef( $vhost->{id} );
    push( @VirtualHost, { "*" => $vhost } );
 
}
$sth->finish();
$dbh->disconnect;
</Perl>

As you can see the script uses all columns from the table to set up the virtual host. You can easily add more columns (e.g. ErrorLog) to the table as long as their name is known to the apache2 configuration.

After you added a new vhost to the database you need to restart the apache server so that the perl script is run and the vhost is set up.

This will create the directories of any vhost which has been added to the table “vhosts” and create a virtual host inside of apache. This is very handy if you need to maintain multiple sites which share the same layout and need basic functionality.