使用nginx為反向代理服務器時,后端應用程序獲取不到請求端口的解決辦法。
以下是nginx 簡單的配置
server {
listen 81;
server_name localhost;
location / {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://127.0.0.1:9380;
}
}
把第5行 的 proxy_set_header Host $host; 修改為 proxy_set_header Host $host:$server_port; 即可。
原因是$host參數不包含端口號導致請求頭部Host中的端口號丟失從而使后端程序不能正確的獲取端口號。
使用 CXF 實現webservice 時 通過nginx 反向代理 動態生成的wsdl文件中 location地址中的端口號也會丟失,從而導致 webservice 調用失敗。
$host 參數的解釋
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.