nginx redirect non-www to www and https for domain.com and subdomain
<p>Im having problems redirecting my non-www urls to www and https.</p>

<p>What I want:</p>

<pre><code>http://domain.com 
http://www.domain.com
https://domain.com
</code></pre>

<p>should redirect to <code>https://www.domain.com</code>.</p>

<pre><code>http://api.domain.com
</code></pre>

<p>should redirect to <code>https://api.domain.com</code></p>

<p>I have seperata ssl keys for domain.com and api.domain.com. SSL settings for api.domain.com is handled via the node.js app. Furthermore domain.com uses a root document and api.domain.com is using proxy_pass to a node.js application on port 1336.</p>

<p>What I tried:</p>

<pre><code># route non ssl api to ssl
server {
    listen 80;
    server_name api.domain.com;
    return 301 https://api.domain.com;
}

# main ssl route for api.domain.com
server {
    listen 443 ssl;

    server_name api.domain.com;

    location / {
        proxy_pass https://localhost:1337;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

# route non ssl to www ssl
server {
    listen       80;
    server_name  www.domain.com domain.com;
    return       301 https://www.domain.com;
}

# route non www ssl to ssl
server {
    listen       443 ssl;
    server_name  domain.com;
    return       301 https://www.domain.com;
}

# main ssl route for domain.com
server {
    listen 443 ssl;

    ssl    on;
    ssl_certificate    /etc/letsencrypt/live/domain.com/fullchain.pem;
    ssl_certificate_key    /etc/letsencrypt/live/domain.com/privkey.pem;

    server_name www.domain.com;

    location / {
        root /var/www/domain.com/www;
    }
}
</code></pre>

<p>Routes which are working as expected:
<a href="https://www.domain.com" rel="nofollow">https://www.domain.com</a>
<a href="http://domain.com" rel="nofollow">http://domain.com</a>
<a href="http://www.domain.com" rel="nofollow">http://www.domain.com</a></p>

<p>Not working:</p>

<p><a href="https://domain.com" rel="nofollow">https://domain.com</a> -> not secure connection, because it's trying to use the cert from api.domain.com (could this be cached, because maybe I tried it before another way, which was wrong) </p>

<p><a href="https://api.domain.com-" rel="nofollow">https://api.domain.com-</a>> redirects to <a href="https://domain.com" rel="nofollow">https://domain.com</a> </p>

<p><a href="http://api.domain.com" rel="nofollow">http://api.domain.com</a> -> redirects to <a href="https://domain.com" rel="nofollow">https://domain.com</a></p>

<blockquote>
  <p>nginx version: nginx/1.4.6 (Ubuntu)</p>
</blockquote>