title: nginx rewrite all wildcard subdomains to www.site.com
body: <p>Using nginx, I want to redirect all subdomains of <code>example.com</code> to <code>www.example.com</code>.</p>
  
  <p>I have seen redirects here to redirect non-www to www or vise versa, but I also want <code>www2.site.com blabla.site.com</code> to be redirected.
  I have a wildcard dns for the domain.</p>
  
  <p>For apache this can be done easily with following:</p>
  
  <pre><code>RewriteCond %{HTTP_HOST} !www.example.com [NC]
  RewriteRule (.*) http://www.example.com%{REQUEST_URI} [R=301,L]
  </code></pre>
  
  <p>The below seem to work, but it is not recommended according to the <a href="http://wiki.nginx.org/IfIsEvil" rel="noreferrer">ifisevil page</a>.</p>
  
  <pre><code>if ($http_host !~ "www.site.com"){
      rewrite ^(.*)$ http://www.example.com$request_uri redirect;
  }
  </code></pre>