title: nginx: redirect to non-www including all subdomains
body: <p>This question has been asked in various ways a million times. Still I can not find an answer that is generic enough to cover all cases.</p>
  
  <p>All I want is to remove <code>www</code> from any incoming URL and I want that applied to all my subdomains. Here is my nginx config that is otherwise working fine:</p>
  
  <pre><code># redirect HTTP to HTTPS, no www
  server {
      listen      80;
      listen [::]:80;
  
      server_name ~^(?&lt;www&gt;www\.)(?&lt;subdomain&gt;.+)\.example\.com$;
  
      # redirect
      return 301 https://${subdomain}.example.com$request_uri;
  }
  
  #redirect HTTPS www to non-www
  server {
      listen 443 ssl http2;
      listen [::]:443 ssl http2;
  
      server_name ~^(?&lt;www&gt;www\.)(?&lt;subdomain&gt;.+)\.example\.com$;
  
      # ssl config...
  
      # redirect
      return 301 https://${subdomain}.example.com$request_uri;
  }
  
  #default server
  server {
      listen 443 ssl http2;
      listen [::]:443 ssl http2;
  
      server_name example.com *.example.com;
  
      # other calls below this point include
      # root dir
      # ssl config
      # security headers
      # various location blocks, specific to my project
      # error page
      # error/access logs...
  }
  </code></pre>
  
  <p>All these mappings are handled fine by the config above:</p>
  
  <ul>
  <li><code>http://example.com</code> -> <code>https://example.com</code></li>
  <li><code>http://client1.example.com</code> -> <code>https://client1.example.com</code></li>
  <li><code>http://dev.client1.example.com</code> -> <code>https://dev.client1.example.com</code></li>
  <li><code>http://stage.client1.example.com</code> -> <code>https://stage.client1.example.com</code></li>
  </ul>
  
  <p>But these are NOT:</p>
  
  <ul>
  <li><code>http://www.example.com</code> -> <code>https://example.com</code></li>
  <li><code>http://www.client1.example.com</code> -> <code>https://client1.example.com</code></li>
  <li><code>http://www.dev.client1.example.com</code> -> <code>https://dev.client1.example.com</code></li>
  </ul>
  
  <p>Can you help me understand what I need to change in my config or how to debug this?</p>