简体   繁体   中英

nginx order of server_name rewrite rules

I'm playing around with nginx rewrite rules using server and server_name . The documentation 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.

I am trying to redirect anything other than www.domain.com (eg www.domain.net , www.domain.info ) to www.domain.com . With the exception of www.domain.de to redirecto to www.domain.com/de .

I have the following rules:

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;
   ...
}

However, it seems like with this ruleset, it will always redirect all non .com domains to www.domain.com/de . Whereas if I flip the first two server segments it works fine.

Am I doing something wrong? Why is the order of the rules important if the server names are explicitly specified?

Using server_name _; to mean 'this is the default server' is a common mistake. It has no special meaning, and you need to use the default_server flag on the listen directive to mark that second server as default:

server {
  listen 80 default_server;
  server_name _;
  rewrite ^ http://www.domain.com$request_uri? permanent;
}

The right configuration would be:

server {
   listen 80;
   server_name domain.de www.domain.de;
   return 301 http://www.domain.com/de$request_uri;
}

server {
   listen 80 default_server;
   server_name _;
   return 301 http://www.domain.com$request_uri;
}

server {
   listen 80;
   server_name "" localhost domain.com www.domain.com;
   ...
}

server_name _; is just a popular stub. The default value of the server_name directive is "" which handles requests without "Host" header. If client doesn't send it at all then server_name "" will leads to redirection loop in a configuration like yours.

Please, take a look at:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM