Nginx & Https Redirection

nginxssl

I have an ssl certificate for www.domain.com.
Obviously if someone goes to https: //domain.com, they will get an error from the browser
about a certificate mismatch. Is it possible to setup the webserver to redirect requests
from https:// domain.com to https:// www.domain.com?

In nginx, I've been trying variations of this, but to no avail:

server {
  listen   443;
  server_name www.domain.com domain.com;
  if ($host !~ www.domain.com) {
    rewrite ^/(.*) https://www.domain.com/$1 permanent;
  }
}

Edit: Just to clarify if anyone hits the site at via plain http, it's not a problem, I already can redirect them to https:// www.domain.com, which is correct. It's only if they manually type https:// domain.com, that I don't know how to do the redirection.

Best Answer

Unfortunately, a redirection response can only take place after the SSL session has been established.

This is clearly a certificate issue; you need a certificate that contains www.domain.com with domain.com as the SAN (Subject Alternative Name). Most CA's give a single SAN for free, e.g., digicert.