I have a number of largely identical configuration files in my Apache2 configuration, for configuring various subdomains. In most of these configuration files, only the name of the subdomain itself is different from the other files and thus I am trying to figure out if it is possible to set some sort of variable at the top of the config file to easily set things like ServerName, DocumentRoot, ErrorLog, CustomLog

A bit like (which obviously doesn't work):

subdomain=blog

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName ${subdomain}.example.com
        DocumentRoot /var/www/${subdomain}.example.com/htdocs

        # Possible values include: debug, info, notice, warn, error, crit, alert, emerg.
        LogLevel warn
        ErrorLog /var/log/apache2/${subdomain}.example.com_error.log
        CustomLog /var/log/apache2/${subdomain}.example.com_access.log combined

        RewriteEngine On
        RewriteCond %{HTTPS} off
        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>

An even smarter solution would be if the subdomain variable can be set through a regex from filename of the configfile.

I did find Dynamically configured mass virtual hosting, but it just doesn't describe exactly what I want.

Running Apache 2.2 on Linux.

share|improve this question

2 Answers

Your most flexible option would be to use some external program to create your Apache configuration based on a template. The traditional program for that on Unix would be M4, although there's probably something a bit less baroque these days.

share|improve this answer

A demo with Perl Template::Toolkit (no need to lear Perl to use the tpage command installed with the module) :

Template file :

$ cat vhost.tpl
<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName [% subdomain %].example.com
        DocumentRoot /var/www/[% subdomain %].example.com/htdocs

        # Possible values include: debug, info, notice, warn, error, crit, alert, emerg.
        LogLevel warn
        ErrorLog /var/log/apache2/[% subdomain %].example.com_error.log
        CustomLog /var/log/apache2/[% subdomain %].example.com_access.log combined
</VirtualHost>

The configuration generation :

$ tpage --define subdomain=domain.tld --interpolate vhost.tpl
<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName domain.tld.example.com
        DocumentRoot /var/www/domain.tld.example.com/htdocs

        # Possible values include: debug, info, notice, warn, error, crit, alert, emerg.
        LogLevel warn
        ErrorLog /var/log/apache2/domain.tld.example.com_error.log
        CustomLog /var/log/apache2/domain.tld.example.com_access.log combined
</VirtualHost>
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.