title: Nginx: redirect non-www to www on https
body: <p>Nginx isn't working to redirect non-www to www if I'm on <code>https</code>:</p>
  
  <p><a href="https://domain.com" rel="nofollow">https://domain.com</a> to <a href="https://www.domain.com" rel="nofollow">https://www.domain.com</a></p>
  
  <p>My curent setup in <code>.conf</code> is:</p>
  
  <pre><code>server {
    listen 80;
    server_name www.domain.com domain.com;
    return 301 https://www.domain.com$request_uri;
  }
  server {
    listen 443;
    server_name domain.com;
    return 301 https://www.domain.com$request_uri;
  }
  server {
    listen IP_ADDRESS:443 ssl;
    server_name www.domain.com;
    ...
  }
  </code></pre>
  
  <p><a href="http://domain.com" rel="nofollow">http://domain.com</a> to <a href="https://www.domain.com" rel="nofollow">https://www.domain.com</a> and <a href="http://www.domain" rel="nofollow">http://www.domain</a> to <a href="https://www.domain.com" rel="nofollow">https://www.domain.com</a> works, but non-www to www on https isn't working.</p>
  
  <p>If I added the IP_ADDRESS on the second <code>server</code> block, I get an error in Chrome (SSL error) and both (www and non-www) stop working.</p>
  
  <p>UPDATE:</p>
  
  <p>Thanks to Steffen (below answer), I updated the self-signed certificate to be <code>*.domain.com</code> and not <code>domain.com</code>.</p>
  
  <p>The <code>.conf</code> file was updated under this format:</p>
  
  <pre><code>ssl_certificate /etc/nginx/ssl/server.crt;
  ssl_certificate_key /etc/nginx/ssl/server.key;
  
  server {
    listen 80;
    server_name www.domain.com domain.com;
    return 301 https://www.domain.com$request_uri;
  }
  server {
    listen 443 ssl;
    server_name domain.com;
    return 301 https://www.domain.com$request_uri;
  }
  server {
    listen 443 ssl;
    server_name www.domain.com;
    ...
  }
  </code></pre>