Let’s Encrypt with dynamic subdomains

apache-2.4lets-encryptvirtualhostwildcard-subdomain

Setup is like this. I've got a domain e.g. example.com
I've setup Apache2 with a VirtualDocumentRoot, this way I can point a subdomain to a specific folder in an easy way:

File sites-available/websites.conf:

ServerName example.com
ServerAlias *.example.com
VirtualDocumentRoot /var/www/websites/%1/

<Directory /var/www/websites/%1/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

So when you visit test.example.com it searches for test folder under websites directory and serves it.

This works as intended, but I wanted to use Let's Encrypt for SSL. Which cannot yet handle wildcard certificates. How would I tackle such a problem?

Current situation:

Installed let's encrypt certs with: sudo certbot --apache -d example.com -d admin.example.com -d www.example.com

File: sites-available/000-default.conf:

DocumentRoot /var/www/websites/current/

<Directory /var/www/websites/current/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<IfModule mod_dir.c>
    DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
</IfModule>

# Let's Encrypt Redirect
RewriteEngine on
RewriteCond %{SERVER_NAME} =example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

All subdomains still get redirected to https. Only topdomain example.com, admin.example.com and www.example.com should be https.

Best Answer

The issue is that you have not scoped any of the configuration in any site-specific way.

It's important to note that the separate config files "per site" is not really an Apache httpd feature. It's just a (relatively common) convention for administrative convenience which in the end uses an Include directive in the main configuration file to merge everything together into a single configuration when the configuration is loaded.

Normally these separate configuration files have all their contents inside VirtualHost to scope their effects, but you seem to have only global configuration, including your http to https redirects.

Related Topic