nginx 400 错误请求(无效主机名)

nginx 400 错误请求(无效主机名)

我已经将 nginx 配置为我构建的 Web 应用程序三个节点上的前端负载均衡器。无论我在upstream.server 和 server.server_name 中使用什么值,nginx 都会不断返回 400/bad request - invalid hostname 错误。我尝试将 localhost 和 127.0.0.1 用于这两个值,并使用匹配的 cURL/Postman 请求发出请求,但无济于事。

我还尝试设置 server.server_name 的值(包括端口号)以更好地匹配传入的 HTTP HOST 标头,但无济于事。

nginx.conf

events {
  worker_connections  1024; 
}

http { 
  upstream myapp {
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003;
  }

  server {
    listen 8000;
    server_name 127.0.0.1;
    location / {
      proxy_pass http://myapp;
    }
  }
}

cURL 请求结果如下(使用 localhost 和 127.0.0.1 没有区别)。

C:\>curl -v http://127.0.0.1:8000/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0)
> GET / HTTP/1.1
> Host: 127.0.0.1:8000
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 400 Bad Request
< Server: nginx/1.17.1
< Date: Mon, 22 Jul 2019 14:29:22 GMT
< Content-Type: text/html; charset=us-ascii
< Content-Length: 334
< Connection: keep-alive
<
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
</BODY></HTML>
* Connection #0 to host 127.0.0.1 left intact

答案1

尝试使用此配置:

events {
  worker_connections  1024; 
}

http { 
  upstream myapp {
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003;
  }

  server {
    listen 8000;
    server_name 127.0.0.1;
    location / {
      proxy_pass http://myapp;
      proxy_set_header Host $host;
    }
  }
}

答案2

我收到了同样的错误,但我在 IIS 前面使用 nginx。但出现问题时有发生。每隔一个请求就会失败,这很奇怪。

事实证明,我已将 IIS 主机名绑定到特定 IP(而不是所有 IP),并且 IIS 正在进行负载平衡,但无法解析其他 IP。

告诉 IIS 绑定到所有 IP 解决了这个问题。只花了几个小时就搞定了。

相关内容