简体   繁体   English

nginx和星号server_name?

[英]nginx and asterisk server_name?

Is there a way to proxy all traffic to a certain server unless the domain is something different? 有没有办法将所有流量代理到某个服务器, 除非该域名不同?

Basically a * for the server_name property? 基本上是*server_name属性?

server {
  listen 80;
  server_name foo.com
}

server {
  listen 80;
  server_name *
}

Or, is there a way to set a "default" server, and then it would use it if none of the other specific server configs match? 或者,有没有办法设置“默认”服务器,然后它会使用它,如果没有其他特定的服务器配置匹配?

You can't use * for server_name . 您不能将*用于server_name From the documentation : 文档

A wildcard name may contain an asterisk only on the name's start or end, and only on a dot border. 通配符名称可能仅在名称的开头或结尾包含星号,并且仅在点边框上包含星号。

However, you can use a regular expression: 但是,您可以使用正则表达式:

server {
    server_name   ~^(www\.)?(.+)$;

    location / {
        root   /sites/$2;
    }
}

As @Valery Viktorovsky's answer says, you can't use a * for server_name . 正如@Valery Viktorovsky的回答所说,你不能使用*来代替server_name You can designate a server block as the "default" to receive all requests which don't match any others. 您可以将server块指定为“默认”,以接收与任何其他请求不匹配的所有请求。 See this post for an explanation. 请参阅此帖子以获得解释。 It would look like this: 它看起来像这样:

server {
    listen 80 default_server;
    server_name wontmatch.com; # but it doesn't matter
}

See the docs for server_name for more. 有关更多信息,请参阅server_name的文档

只是一个快速更新......根据文档,通配符现在可以正常工作: http//nginx.org/en/docs/http/server_names.html

FYI, for those like me who were looking for something a little different, the following configuration will listen and respond to all port 80 request whether you use IP or URL (AKA everything): 仅供参考,对于像我这样寻找一些不同的东西的人,以下配置将监听并响应所有端口80请求,无论您使用IP还是URL(AKA所有内容):

server {
    listen 80 default_server;
    server_name _;
...
}

Taken from: http://nginx.org/en/docs/http/server_names.html 摘自: http//nginx.org/en/docs/http/server_names.html

In catch-all server examples the strange name “_” can be seen: 在catch-all服务器示例中,可以看到奇怪的名称“_”:

server { listen 80 default_server; server {listen 80 default_server; server_name _; 服务器名称 _; return 444; 返回444; } There is nothing special about this name,... 这个名字没什么特别的,......

You will get errors on sudo service nginx restart or ... start while /etc/nginx/sites-enabled/default symbolic link is still active since it uses the same matching pattern. /etc/nginx/sites-enabled/default符号链接仍处于活动状态时,您将在sudo service nginx restart... start时出现错误,因为它使用相同的匹配模式。 Simply remove that link and everything should work. 只需删除该链接,一切都应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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