Nginx – use variables in Nginx server block for SSL Cert and Key file

configurationnginxreverse-proxysslvirtualhost

I'm using Nginx Apache Reverse Proxy, I have multiple VHOSTS and I want to serve them all in a single nginx vhost file with support for SSL.

My server block is

    server {
    listen 80;
    server_name _;

    root   /var/www/$host/web;


    access_log  /var/log/mylogs/httpd/$host/access.log; 

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        proxy_pass http://SERVERIP:8090;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~ /\. {
        deny all;
    }


}

This is working well without SSL for all sites BUT
when I do the same for SSL support below:

    server {
    listen 80;
    server_name _;

    ssl on;
    ssl_certificate /var/www/$host/ssl/$host-le.crt;
    ssl_certificate_key /var/www/$host/ssl/$host-le.key;
    root   /var/www/$host/web;


    access_log  /var/log/mylogs/httpd/$host/access.log; 

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        proxy_pass http://MYIP:8090;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~ /\. {
        deny all;
    }

}

I got errors something like this

ssl_certificate /var/www/$host/ssl/$host-le.crt not found
nginx config test failed

My vhost web files are in this format

/var/www/domain1.com/web
/var/www/domain2.com/web
/var/www/domain3.com/web

and their ssl cert and keys are in

/var/www/domain1.com/ssl
/var/www/domain2.com/ssl
/var/www/domain3.com/ssl

Please help me, I'm noob and still learning….

Best Answer

Use $ssl_server_name variable instead of $host.
It can be used since Nginx 1.15.9 and OpenSSL 1.0.2 version. http://nginx.org/ru/docs/http/ngx_http_ssl_module.html

ssl_certificate     $ssl_server_name.crt;
ssl_certificate_key $ssl_server_name.key;