Wildcard Subdomains: Multi-tenancy in Nginx

Here we use LetsEncrypt (certbot) with the CloudFlare DNS plugin to generate a free, auto-renewing TLS certificate to use with Nginx.

Then we configure Nginx to use that TLS certificate and create a configuration to support multi-tenancy in our applications.

We use a special configuration to capture the value of the subdomain so we can pass it off to our PHP application (or do anything we want, like use dynamic app locations for local development - as described here: https://www.youtube.com/watch?v=SPHxW1C4G6I ).

Useful Links:

Install certbot: https://certbot.eff.org/ Certbot challenge types: https://letsencrypt.org/docs/challenge-types/ My site: fideloper.com My newsletter: https://fideloper.ck.page/

Install and Configure Certbot

We can start by installing/configuring Certbot. In our case, we'll use the Cloudflare plugin to manage DNS.

Why do we need to manage DNS? Certbot uses a DNS challenge for wildcard subdomains (instead of the HTTP challenge for non-wildcard domains).

# Install certbot on Ubuntu as per
# https://certbot.eff.org/instructions?ws=nginx&os=snap

sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

sudo snap set certbot trust-plugin-with-root=ok
sudo snap install certbot-dns-cloudflare

We'll run stuff as user root, so we'll configure a location to save credentials to the Cloudflare API.

You'll need to generate an API token in Cloudflare (you can lock them down to be specific to managing one domain's DNS). Docs on that are here.

Create file /root/.secrets/cloudflare.ini and add something like:

dns_cloudflare_api_token = 0123456789abcdef0123456789abcdef01234567

Then we can generate our wildcard certificate!

# Optionally add --force-renewal if
# a current certificate is generated and
# you want to over-write it
sudo certbot certonly \
    --dns-cloudflare \
    --dns-cloudflare-credentials /root/.secrets/cloudflare.ini \
    --post-hook "service nginx reload" \
    --non-interactive \
    --agree-tos \
    --email your-email-here \
    -d *.your-domain.tld \
    -d your-domain.tld

Check out the video for more details on all of this.