Nginx – Sharing two SSL certificates with as wildcard and root domains in nginx (same server)

nginxopensslsslssl-certificatewildcard-subdomain

I have purchased a wildcard certificate and a single certificate for my domain structure which is:

app.example.com => single
*.app.example.com => wildcard

Both these routes should point to the same project directory on same server

Note: RapidSSL Support said that I had to purchase two as unlike classic domains example.com, my one is app.example.com, so that wildcard won't care my 3 decimal root

Now, I need to setup in nginx two different certificates. My default one (which works for my wildcard), however not 'app.example.com' as its ssl certificate is not included.

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;

    ssl on;
    ssl_certificate /etc/ssl/ssl_certificate.cer;  // this is my wildcard cert
    ssl_certificate_key /etc/ssl/private.key;


    root /var/www/example/public;
    index index.php index.html index.htm;

    server_name .app.example.com;

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

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }
 }

 // And for redirect:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name .app.example.com;
    return 301 https://$server_name$request_uri;
}

How can I divide this into two and include my new certificate for app.example.com and keep wildcard as this?

Best Answer

Use two server blocks, one for the single domain and one for the wildcard domain. Specify the appropriate server_name and ssl_certificate directives.

server {
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name *.app.example.com;    
    ssl_certificate /etc/ssl/ssl_certificate1.cer;
    ssl_certificate_key /etc/ssl/private1.key;

    ...
}
server {
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name app.example.com;    
    ssl_certificate /etc/ssl/ssl_certificate2.cer;
    ssl_certificate_key /etc/ssl/private2.key;

    ...
}

See this document for details.

You can use an include directive to pull common configuration into each block from some other file.