Secure, Wildcard Subdomain Hosting (Apache)

This is the configuration I have running right now on this server to serve new subdomains under paigejulianne.com by simply creating a directory on the filesystem.

The first step is to write a basic config file that just directs everything to SSL. On my Ubuntu 22.04 system, I have the following contents at /etc/apache2/sites-enabled/paigejulianne.conf

<VirtualHost *:80>
        ServerName paigejulianne.com
        ServerAlias *.paigejulianne.com
        DocumentRoot "/srv/paigejulianne.com"
        RewriteEngine on
        RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
</VirtualHost>

Next is to generate a wildcard certificate. I use Certbot and the command is simply:

certbot certonly --preferred-challenges=dns -d "*.paigejulianne.com,paigejulianne.com" --manual

During this process, you’ll need to create a TXT record for _acme-challenge.<domain>. Certbot will tell you what it expects before creating the certificate. You need to make sure this record resolves before continuing Certbot. One quick way to do that is to run nslookup -q=TXT _acme-challenge.<domain>

In my case, the certificate and key file were generated at /etc/letsencrypt/live/paigejulianne.com-0001. I also want to serve subdomains out of /srv/subs/<subdomain>. So, I’m going to add the following lines to /etc/apache2/sites-enabled/paigejulianne.conf

Any “one-off” hosts (like wiki.paigejulianne.com) MUST go before the wildcard VirtualHost block, or it will not be served correctly.

<VirtualHost *:443>
        ServerName paigejulianne.com
        ServerAlias www.paigejulianne.com
        DocumentRoot "/srv/paigejulianne.com"

        Include /etc/letsencrypt/options-ssl-apache.conf
        SSLCertificateFile /etc/letsencrypt/live/paigejulianne.com-0001/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/paigejulianne.com-0001/privkey.pem
</VirtualHost>

<VirtualHost *:443>
        ServerAlias *.paigejulianne.com
        UseCanonicalName Off
        VirtualDocumentRoot /srv/subs/%1

        Include /etc/letsencrypt/options-ssl-apache.conf
        SSLCertificateFile /etc/letsencrypt/live/paigejulianne.com-0001/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/paigejulianne.com-0001/privkey.pem
</VirtualHost>

Obviously, you’ll need to restart Apache after editing your config.

Now, if I want to serve something at https://test.paigejulianne.com, all I need to do is drop the files into /srv/subs/test. No need to write a new Apache config or create new certificates.