Redirect https://example.com to https://www.example.com

We got a wildcard certificate from Thawte and this isn't valid for https://example.com.

So we'd like like to forward all requests from https://example.com to https://www.example.com without getting a cert-error.

Is this possible in nginx?

my configuration:

server {
    listen 80;

    server_name example.ch
                www.example.ch
                api.example.ch;

    if ($host = 'example.ch' ) {
        rewrite  ^/(.*)$  https://www.example.ch/$1 permanent;
    }

    rewrite ^ https://$server_name$request_uri? permanent;
}

server {
    listen 443;

    if ($host = 'example.ch' ) {
        rewrite  ^/(.*)$  https://www.example.ch/$1 permanent;
    }

    ssl on;
    ssl_certificate      /etc/nginx/ssl/example.crt;
    ssl_certificate_key  /etc/nginx/ssl/example.key; 

    server_name example.ch
                www.example.ch
                api.example.ch;

    ...
}

It isn't possible, full stop. SNI notwithstanding, a browser told to go to https://example.com is going to get mighty grumpy about being redirected anywhere else before any valid certificate has been presented for example.com - if it didn't, SSL certificates would be substantially pointless.

As others have pointed out, there is no way to support this without getting a certificate that is in some way valid for the initially-requested domain.