Nginx load certificate files based on host

Jon Riel asked:

I want to serve the right ssl certificate based on the $host variable with an exception for any host being *.mydomain.com or mydomain.com

The certificates fall in two groups:

  1. Local certificates: *.mydomain.com mydomain.com
  2. External certificates: www.user1.com www.user2.com

It is important to know that www.user1.com and www.user2.com are set with CNAME to point to user1.mydomain.com and user2.mydomain.com, meaning they are being caught by the same server section that handles *.mydomain.com but the value of $host stays www.user1.com or www.user2.com. That means I’ve got to deal with this in one server {} block.

Based on that I want to have an if-statement that checks whether the $host variable is a subdomain of *.mydomain.com or mydomain.com and load my certificate. If not, I want to check whether the certificate of a user exists in /etc/$host/certificate and load that.

I’m vaguely familiar with nginx and I’ve read of the dislike of if-statements and now I’m wondering what the best way would be to get this done. I’ve got a lot done and this last step is just what’s left.

My answer:


Hosts that are all served by the same server block should use the same certificate. Have your certificates reissued or create a duplicate server block.

Supposedly in nginx 1.16 it is possible to use a variable to specify the ssl certificate to use, but I have never found anyone who managed to make this work. In any event, you can only put the directive in the server block, it does not work inside if.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.