nginx: Redirect https traffic without subdomain to subdomain (non-www to www)

My current ssl certificate covers the subdomains www.example.com and static.example.com

So if a users try to access my site via https://example.com I want to redirect him to https://www.example.com .

How can I do that within in my nginx conf?

I know that similiar questions have been asked here, but I could not find the solution here.


Solution 1:

First of all, you should get a certificate valid both for example.com and www.example.com (you can get it for free from StartSSL or WoSign). Then make sure you got SNI enabled in your nginx (should be there by default). Then just add the following to your nginx.conf:

server {
    listen 0.0.0.0:443 ssl spdy;
    listen [::]:443 ssl spdy;
    listen 0.0.0.0:80;
    listen [::]:80;
    ssl_certificate /etc/ssl/example.com.crt;
    ssl_certificate_key  /etc/ssl/example.com.key;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}