title: Nginx redirect http subdomains to https
body: <p>I have one domain with 3 subdomains:</p>
  
  <pre>
   - example.com (main domain)
   - api.example.com
   - blog.example.com
   - support.example.com (just a cname to point to zendesk)
  </pre>
  
  <p>And I have this 3 configuration on my <b>Nginx</b>:</p>
  
  <p><b>api</b></p>
  
  <pre><code># HTTP server
  server {
      listen       80;
      server_name  api.example.com;
      return 301 https://api.example.com$request_uri;
  }
  
  
  # HTTPS server
  server {
      ssl          on;
      listen       443;
      server_name  api.example.com;
  
      ssl_certificate APIcert.crt;
      ssl_certificate_key APIcert.key;
  
      #root configuration.....
  }
  </code></pre>
  
  <p><b>blog</b></p>
  
  <pre><code>server {
      listen 80;
      server_name blog.example.com;
  
      root /var/www/blog;
      index index.php index.html index.htm;
  </code></pre>
  
  <p><b>site/main domain</b></p>
  
  <pre><code>server {
      listen 80;
      listen 443 ssl;
      server_name www.example.com;
      return 301 https://example.com$request_uri;
  
      location ~ \.(php|html)$ {
          deny  all;
      }
  }
  
  server {
      listen 80;
      server_name example.com;
      return 301 https://example.com$request_uri;
  
      location ~ \.(php|html)$ {
          deny  all;
      }
  }
  
  server {
      ssl on;
      listen 443 ssl;
      ssl_certificate  mycert.crt;
      ssl_certificate_key  mycert.key;
      server_name example.com;
  
      root /var/www/frontend;
      .....
  }
  </code></pre>
  
  <p><b>MY PROBLEM</b>:</p>
  
  <ul>
  <li>The subdomain api.example is OK!</li>
  <li>The main domain <a href="http://example.com" rel="nofollow">http://example.com</a> and <a href="https://example.com" rel="nofollow">https://example.com</a> is OK!</li>
  <li>If I try to access the main domain with www on HTTP the browser redirect correct to <a href="https://example.com" rel="nofollow">https://example.com</a>. But when I try to access the main domain with www and https, <a href="https://www.example.com" rel="nofollow">https://www.example.com</a>, the browser try to access the SSL CERT from api.</li>
  <li>And after I try to access the main domain and redirect to HTTPS my other subdomains that doesn't have HTTPS is redirect to https and show error, because they tried to use SSL CERT from api.</li>
  <li>Example: if I try to access <a href="http://blog.exemple.com" rel="nofollow">http://blog.exemple.com</a>, firefox redirect to <a href="https://blog.example.com" rel="nofollow">https://blog.example.com</a> and show SSL error.</li>
  <li>This is a video showing <a href="https://www.screenmailer.com/v/Bz6j8FmAywSCag8" rel="nofollow">this problem</a></li>
  <li>The domain is online, you can test on <a href="http://blog.alooga.com.br" rel="nofollow">http://blog.alooga.com.br</a>, <a href="http://alooga.com.br" rel="nofollow">http://alooga.com.br</a> </li>
  </ul>