title: nginx order of server_name rewrite rules
body: <p>I'm playing around with nginx rewrite rules using <code>server</code> and <code>server_name</code>. The <a href="http://wiki.nginx.org/HttpCoreModule#server_name" rel="nofollow">documentation</a> sounds simple and clear enough about the order of precedence, but I'm getting some slightly odd behaviour and want to check whether I missed anything.</p>
  
  <p>I am trying to redirect anything other than <code>www.domain.com</code> (e.g. <code>www.domain.net</code>, <code>www.domain.info</code>) to <code>www.domain.com</code>. With the exception of <code>www.domain.de</code> to redirecto to <code>www.domain.com/de</code>.</p>
  
  <p>I have the following rules:</p>
  
  <pre><code>server {
     server_name domain.de www.domain.de;
     rewrite ^(.*) http://www.domain.com/de$1 permanent;
  }
  
  server {
     server_name _;
     rewrite ^(.*) http://www.domain.com$1 permanent;
  }
  
  server {
     listen 80;
     server_name localhost domain.com www.domain.com;
     ...
  }
  </code></pre>
  
  <p>However, it seems like with this ruleset, it will always redirect <em>all</em> non <code>.com</code> domains to <code>www.domain.com/de</code>. Whereas if I flip the first two <code>server</code> segments it works fine.</p>
  
  <p>Am I doing something wrong? Why is the order of the rules important if the server names are explicitly specified?</p>