[英]nginx order of server_name rewrite rules
I'm playing around with nginx rewrite rules using server
and server_name
. 我在玩使用
server
和server_name
nginx重写规则。 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
. 我正在尝试将
www.domain.com
以外的任何其他内容(例如www.domain.net
, www.domain.info
)重定向到www.domain.com
。 With the exception of www.domain.de
to redirecto to www.domain.com/de
. 除了
www.domain.de
,重定向到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
. 但是,似乎与此规则集一样,它将始终将所有非
.com
域重定向到www.domain.com/de
。 Whereas if I flip the first two server
segments it works fine. 而如果我翻转前两个
server
段,则可以正常工作。
Am I doing something wrong? 难道我做错了什么? Why is the order of the rules important if the server names are explicitly specified?
如果显式指定服务器名称,为什么规则顺序很重要?
Using server_name _;
使用
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: 它没有特殊含义,您需要在listen指令上使用
default_server
标志将第二台服务器标记为默认服务器:
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.
server_name伪指令的默认值为“”,它处理没有“ Host”头的请求。 If client doesn't send it at all then
server_name ""
will leads to redirection loop in a configuration like yours. 如果客户端根本不发送消息,则
server_name ""
将导致像您这样的配置中的重定向循环。
Please, take a look at: 请看一下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.