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.


1 Answer 1


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.

  • Oh no, I fear I cannot make this work as there is a CDN layer on top which made everything complicated.
    – Jon Riel
    May 16, 2019 at 20:23
  • I tried to create a second server block but it doesn't catch the request and instead it's going to the wildcard one. www.user1.com -> (CNAME) -> user1.mydomain.com -> CDN -> myserver
    – Jon Riel
    May 16, 2019 at 20:32
  • the alternative would be to not have a catch-all *.mydomain and hard-code every subdomain in a server block. With thousands of subdomains, would you advise doing that?
    – Jon Riel
    May 16, 2019 at 21:02
  • @JonRiel I have a site with a few hundred server blocks. It's going to get redone before it gets to 1000. May 17, 2019 at 1:10
  • I have now changed the configuration in collaboration with the CDN host (they now issue the certificates and handle that), so for those looking for answers to this problem, I think we have to wait for nginx to mature the $variables in the certificate path
    – Jon Riel
    May 17, 2019 at 10:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.