NGINX rewrite rules for sub subdomains

No, sorry, that isn’t going to be possible.

Assuming the user connects to your server at https://www.sub.domain.com with HTTPS, the sequence of events will be:

  1. the user’s client makes a connection and initiates an SSL negotiation; they will send SNI (= server name indication) that they’re connecting to www.sub.domain.com
  2. the server can use the SNI to choose which certificate it will respond with, but cannot use it to redirect the client. So it picks the best one it’s got – ‘sub.domain.com’ without the ‘www’
  3. the client validates the certificate: chain, valid date, URL – and decides that it does not match and creates a browser warning.
  4. if the client clicks through the error, we then have an established secure connection and only then can we send HTTP redirects.

So you’d need a redirect at step 2 but that’s not possible. (If instead they do connect over HTTP not HTTPS then you can redirect from here, yes, but that’s not the certificate warning case you asked about.)

What options you do have is going to depend on the amount of control you have over your hosting environment.

  • if you have a shell account onto the server and full control over the web server for your sites (which probably means root access, but may not on well designed shared hosting), then you can get a separate SSL certificate from Let’s Encrypt or similar to use instead, which you will be able to configure with all the ‘www’ versions of the domains provided your server is set up to serve them
  • if you can’t make Let’s Encrypt’s validation work but can install your own SSL certificates, you can go to a third party certificate authority and buy one that covers everything you need. This might cost a few dollars, or maybe tens of dollars at most. Depending on how much flexibility you have with the configuration you might be able to use the existing free certificate for sub.domain.com and just buy one for www.sub.domain.com
  • or you can try and get better help from your web host. I don’t know where they get their certificates from but it ought to be possible to do this for you
  • or you can put a CDN in front of your site, e.g. CloudFront or similar; then you’re relying on them to handle the initial SSL and you might be able to convince them to support www too
  • or you can just try and quietly drop support for www.sub.domain.com – maybe it’s not worth worry about it no-one actually uses that, and it should be easy to convince anyone that looks that “This certificate was issued by sub.domain.com not www.sub.domain.com” is OK to click through

or there’s probably more!