大网数据广告活动
服务器运维问答

What is the difference between server_name _ and server_name "" in Nginx?

· 52CE 我爱测

I want to set a default catch-all server block to handle any host names that do not match my exact server_name values. But I'm unsure which one should I use. server { listen 80 default_server; server_name ""; # this is by default…

问题原文

原帖链接 · NARKOZ · CC BY-SA 4.0

I want to set a default catch-all server block to handle any host names that do not match my exact server_name values. But I'm unsure which one should I use.

server {
    listen 80 default_server;
    server_name ""; # this is by default if no server_name specified
    return 444;
}

or

server {
    listen 80 default_server;
    server_name _;
    return 444;
}

I've tested and they seem to behave equally. Is there any difference between them?

社区高分解答

原帖链接 · Pramod Singh · CC BY-SA 4.0

Short answer: Yes, there is difference between server_name ""; and server_name _;

Long answer: server_name ""; defines a match for a request without host header since 0.8.48 and it has been supported since 0.7.12.

https://nginx.org/en/docs/http/request_processing.html

If requests without the “Host” header field should not be allowed, a server that just drops the requests can be defined:

server {
    listen      80;
    server_name "";
    return      444;
}

Here, the server name is set to an empty string that will match requests without the “Host” header field, and a special nginx’s non-standard code 444 is returned that closes the connection.

On the other side, server_name _; defines an invalid server names which never intersect with any real name. It is just a non-match. So in the event of no matches, nginx will select the first server{} block and use that.

To conclude, you can use server_name _; for catch-all server block but not server_name "";.

Reference - https://stackoverflow.com/questions/9454764/nginx-server-name-wildcard-or-catch-all https://blog.gahooa.com/2013/08/21/nginx-how-to-specify-a-default-server/

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-06-02)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。