如何使用错误的 Host 标头集阻止请求?

bde*_*ham 13 nginx

我使用 nginx 来服务我的网站。我想阻止所有带有与我的站点域不匹配的 HTTP“主机”标头的请求。

更具体地说,我的 nginx.conf 包含这两个服务器块:

server {
    # Redirect from the old domain to the new domain; also redirect
    # from www.newdomain.com to newdomain.com without the "www"
    server_name www.olddomain.com olddomain.com www.newdomain.com;
    listen 80;
    return 301 $scheme://newdomain.com$request_uri;
}

server {
    server_name newdomain.com localhost;
    listen 80;

    # Actual configuration goes here...
}
Run Code Online (Sandbox Code Playgroud)

我想阻止(即“返回”444 状态代码)主机不是 www.olddomain.com、olddomain.com、www.newdomain.com 或 newdomain.com 的任何流量。我怎样才能做到这一点?

AD7*_*six 16

定义默认服务器

如果您没有明确定义默认服务器,nginx 将隐式使用 first-found server。因此,只需创建一个服务器块来阻止未知主机

server {
  listen 80 default_server;
  return 444;
}
Run Code Online (Sandbox Code Playgroud)

(不,没有必要添加 server_name - 因为它永远不会匹配)。