Skip to content
Go back

Dynamic SSL certificate for Nginx web server

Updated: 

If you are configuring CI/CD, there is a high chance that you want to dynamically set certificates for different subdomains on staging server. This is pretty straightforward process and requires little setup to work properly.

Table of Contents

Open Table of Contents

Prerequisites

We will assume that

Setting up .conf file

To set SSL certificate for connection, we use two directives:

server {
    #...
    ssl_certificate /etc/letsencrypt/live/certificate/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/certificate/privkey.pem;
    #...
}

Since specified in prerequisites Nginx and OpenSSL versions are supporting variables for those directives, we just need to extract our branch + domain name. We can do this with simple regular expression in map before server directive:

map $ssl_server_name $certname {
    default $ssl_server_name;
    ~^(subdomain1\.|subdomain2\.)?(((?<branch>(?!subdomain1|subdomain2).+)\.|)staging\.com)$ $2;
}

You can thorougly study this regular expression on regex101.com. What this snippet does is basically extracting “branch + staging.com” string to $certname variable. We can then use this variable for our SSL certificates:

server {
    #...
    ssl_certificate /etc/letsencrypt/live/$certname/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$certname/privkey.pem;
    #...
}

Why you can’t just use $ssl_server_name

You actually can, this is an example of advanced setup for staging/testing environment with multiple deployments and multiple subdomains for each deployment. You can read more in Managing multiple SSL certificates for staging web server article.


Share this post on:

Previous article
Guide to HTML dark mode responsive images
Next article
Rounded gradient borders with transparent backgrounds in CSS