Using Apache mod_macro
Apache mod_macro can be used to simplify Apache configurations on servers with large number of identically configured VirtualHosts.
Create your macro configuration. In this example we create two macros, one for http & one for https. You should only enable one of these, and if https is enabled http is automatically redirected to https. Unless the requests starts with /.well-known/acme-challenge/ which is used by Let’s Encrypt for creating & renewing certificates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<Macro VHostHTTP $vhost> <VirtualHost *:80> ServerName $vhost ServerAlias www.$vhost DocumentRoot /var/www/$vhost/htdocs ScriptAlias /cgi-bin/ /var/www/$vhost/cgi-bin/ </VirtualHost> </Macro> <Macro VHostHTTPS $vhost> <VirtualHost *:80> ServerName $vhost ServerAlias www.$vhost <Location "/"> <If "%{REQUEST_URI} !~ m#^/.well-known/acme-challenge/#"> Redirect 301 "https://%{HTTP_HOST}%{REQUEST_URI}" </If> </Location> DocumentRoot /var/www/$vhost/htdocs </VirtualHost> <VirtualHost *:443> ServerName $vhost ServerAlias www.$vhost DocumentRoot /var/www/$vhost/htdocs ScriptAlias /cgi-bin/ /var/www/$vhost/cgi-bin/ SSLCertificateFile /etc/letsencrypt/live/$vhost/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/$vhost/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateChainFile /etc/letsencrypt/live/$vhost/chain.pem </VirtualHost> </Macro> |
Enable mod_macro. This will both enable loading the module, and load the newly created configuration.
1 2 |
a2enmod macro service apache2 restart |
Create your virtualhost configuration. You could create one of these per site or create a single master configuration that includes all of your virtualhosts, one per line. First enable VHostHTTP, then once you’ve provisioned a Let’s Encrypt certificate change it to VHostHTTPS.
1 |
Use VHostHTTPS example.com |
Reload Apache to enable your new virtualhost:
1 2 |
a2ensite example.com service apache2 reload |
Thanks for the guide, sadly certbot doesn’t support mod_macro so I’m back to creating multiple files.
The above configuration using mod_macro with certbot works for me. Certbot itself doesn’t know anything about mod_macro, it just creates the certs. Then you use the above mod_macro config to enable individual virtualhosts. You do need to create an individual apache virtualhost config for each site, but with mod_macro that config becomes a simple one-liner that automatically enables https with the Let’s Encrypt certificate.