1.websocket
WebSocket 是一種網絡通信協議,它提供了在單個 TCP 連接上進行全雙工(雙向)通信的能力
假設需求:
把 ws://192.168.0.1:8088/ws-api/websocket/pushData代理到ws://192.168.0.156:8888/websocket/pushData;同時,在轉發時去除ws-api前綴.
2.使用Nginx代理WebSocket
# WebSocket 代理配置location ^~ /ws-api/ {proxy_pass http://192.168.1.156:8888/; # 寫真實的服務器地址proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "Upgrade";proxy_set_header Host $host;proxy_read_timeout 86400;proxy_set_header X-Real-IP $remote_addr; # 傳遞客戶端真實IPproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}
- WebSocket 關鍵配置
proxy_http_version 1.1
:強制使用HTTP 1.1
協議與后端通信。WebSocket
協議依賴HTTP 1.1
的Upgrade
機制完成握手。Nginx
默認使用HTTP 1.0
與后端通信,無法支持協議升級。proxy_set_header Upgrade $http_upgrade
:將客戶端的Upgrade
請求頭透傳給后端服務器。$http_upgrade
變量捕獲客戶端請求中的Upgrade
頭(通常為websocket
)。后端服務器需通過Upgrade
:websocket
頭識別WebSocket
握手請求。proxy_set_header Connection "upgrade"
:修改Connection
請求頭為upgrade
,指示后端啟用協議升級。與Upgrade
頭配合,告知后端需要將連接從HTTP
升級為WebSocket
。
- 其他配置:
proxy_read_timeout 86400
設置長時間連接不超時;X-Real-IP
和X-Forwarded-For
頭用于傳遞客戶端真實IP
,方便后端服務獲取客戶端信息。
!!!注意:ws://192.168.0.1:8088/ws-api/websocket/pushData 前面的 ws://192.168.0.1:8088 不用去掉,并且這個ip地址必須是當前nginx 服務器所在的ip地址才行。