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 * or

The certificates fall in two groups:

  1. Local certificates: *
  2. External certificates:

It is important to know that and are set with CNAME to point to and, meaning they are being caught by the same server section that handles * but the value of $host stays or 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 * or 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.