title: nginx wildcard subdomain ssl rewrite
body: <p>Have a wildcard dns subdomain record. Using domain-only validation SSL certificate.
  Need to set nginx rewrite rules in that way:</p>
  
  <pre><code>http://site.com   =&gt; https://site.com
  
  http://*.site.com =&gt; http://*.site.com
  </code></pre>
  
  <p>I guess it is something like this</p>
  
  <pre><code>server {
      listen  80;
      server_name site.com *.site.com;
      if ($host ~* "^([^.]+(\.[^.]+)*)\.site.com$"){
          set $subd $1;
          rewrite ^(.*)$ http://$subd.site.com$1 permanent;
          break;
      }
      if ($host ~* "^site.com$"){
          rewrite ^(.*)$ https://site.com$1 permanent;
          break;
      }
      #rewrite    ^ https://$server_name$request_uri? permanent;
      charset utf-8;
  }
  
  server {
  
      listen   443;
  
      server_name  site.com;
      ssl On;
      ssl_certificate     /root/site.com.crt;
      ssl_certificate_key /root/site.com.key;
  
      location ~ \.php$ {
          fastcgi_pass   127.0.0.1:8888;
          fastcgi_index  index.php;
          fastcgi_param  SCRIPT_FILENAME  /var/www/site$fastcgi_script_name;
          fastcgi_param  QUERY_STRING     $args;
          include fastcgi_params;
      }
  
      location / {
          root   /var/www/site;
          index  index.php index.html;
          if ($host !~ ^(site.com)$ ) {
              return 444;
          }
          try_files $uri $uri/ /index.php?$args;
      }
  }
  </code></pre>
  
  <p>It loops infinitely. What is the correct way to get this working ?</p>