How to dynamically set SSL certificate for Nginx web server for staging/testing environment
If you are configuring CI/CD, there is a high chance that you want to dynamically set certificates for different subdomains on testing or staging server. This is pretty straightforward process and requires little setup to work properly.
Prerequisites
We will assume that
- Server uses Nginx 1.15.9 or higher;
- Branches are deployed to
/var/www/subdomains/$branch
; - Domain for server is
staging.com
; - Each branch can be accessed via
https://${branch}.staging.com
, and their subdomains viahttps://${subdomain}.${branch}.staging.com
; - Server has OpenSSL 1.0.2 or higher installed;
- Certificates are issued with
certbot
for${branch}.staging.org
and${subdomain}.${branch}.staging.com
; staging.conf
is an entry point for all our deploymentsis and is in Nginx’ssites-enabled
directory.
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 evnironment with multiple deployments and multiple subdomains for each deployment. You can read more in Managing SSL certificates for Nginx web server for staging/testing environment article.