前言

  • nginx version: nginx/1.20.1
  • CentOS Linux release 7.9.2009 (Core)

server_name _ 是啥意思?

server_name _没啥意思。我觉得应该把这个替换掉。

假设配置是这样的

nginx.conf

...
http {
    ...

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        ...
    }
}
...

/etc/nginx/default.d/目录下包含2个conf:

  • domainA.conf
  • domainB.conf

nginx中有3个server_name,且生效顺序如下:

  • domainA
  • domainB
  • _

当访问 http://localhost 时

当访问 http://localhost 时,展示/usr/share/nginx/html/index.html的内容。
localhost_匹配了(_=localhost)。

当访问 http://127.0.0.1 时

当访问 http://127.0.0.1 时,展示domainA的内容。
127.0.0.1domainA匹配了( 127.0.0.1 无法与三者之中的任何一个匹配,默认选取第一个)。

当访问 http://domainA 时

当访问 http://domainA 时,展示domainA的内容。

当访问 http://domainB 时

当访问 http://domainB 时,展示domainA的内容。

_=localhost

server_name _;server_name localhost; 等效

server_name 默认配置

nginx.conf中的顺序改为:

...
http {
    ...
    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        ...
    }
    
    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
}
...
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐