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 解決了這個問題。只花了幾個小時就弄清楚了。

相關內容