Ye' Olde Site By Joby

Update to my ideal Apache VirtualHost settings for automatic subdomains

I've updated my Apache config since the post I made yesterday about creating subdomains based on directory names. The revisions are fairly small, but important. Since yesterday I moved my DNS nameservers to a new provider who doesn't offer redirects the way Namecheap did, so I had to get my own configuration to gracefully handle redirecting to, both with and without SSL.

# Set up the basic settings for the whole site
<Directory "/home/www/">
    Options None
    AllowOverride All
    Order allow,deny
    Allow from all

# This section redirects all requests on port 80 to HTTPS
<VirtualHost *:80>
    RewriteEngine on
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

# This section catches all requests on port 443 and sets
# their VirtualDocumentRoot to be a subdirectory of
# named for the requested subdomain
<VirtualHost *:443>
    VirtualDocumentRoot /var/www/
    # Redirect to www if there's no subdomain
    RewriteEngine on
    RewriteCond %{SERVER_NAME} ^$
    RewriteRule ^{REQUEST_URI} [END,NE,R=permanent]
    # The next 3 lines pull the necessary certificates and config from Lets Encrypt
    SSLCertificateFile /etc/letsencrypt/live/
    SSLCertificateKeyFile /etc/letsencrypt/live/
    Include /etc/letsencrypt/options-ssl-apache.conf

I also hit some snags with the way Let's Encrypt issues wildcard certificates in a way that prevents them from working on the root domain (i.e. my certificate was working for all my subdomains, but not just, but that's a story for another day.

Tags: #apache #webdev


Categories: blog posts

Page metadata

Date created
October 2, 2020
Date modified
October 2, 2020
HTML copy built
October 2, 2020, 10:02 pm MDT