問題記錄:本地socket測試無誤后部署發現 WebSocket connection to "xxx/xxx" failed
解決方案:
在nginx.conf的http模塊添加如下內容
map $http_upgrade $connection_upgrade { default upgrade; '' close; }
其次在反向配置中Nginx Location下添加如下代碼
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
從版本1.3.13開始,nginx實現特殊的操作模式,如果代理服務器返回帶有代碼101(交換協議)的響應,則允許在客戶端和代理服務器之間建立隧道,
並且客戶端要求通過請求中的“升級”標頭:Nginx官網
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream jiaxun.com {
server localhost:8082;
}
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
location /realtime/websocket {
proxy_pass http://jiaxun.com;
proxy_http_version 1.1;
proxy_connect_timeout 4s;
proxy_read_timeout 3600s; #默認60s沒有傳輸數據就會關閉,延長時間
proxy_send_timeout 12s;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
配置二
location /websocket {
proxy_pass http://127.0.0.1:8095/websocket;
#注意:使用代理地址時末尾記得加上斜杠"/"。
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 600s;
}
WebSockets應用程序會在客戶端和服務器之間建立一個長連接,使得開發實時應用很容易。
HTTP的Upgrade協議頭機制用於將連接從HTTP連接升級到WebSocket連接,Upgrade機制使用了Upgrade協議頭和Connection協議頭。
反向代理服務器在支持WebSocket協議方面面臨着一些挑戰。
挑戰之一是WebSocket是一個逐段轉發(hop-by-hop)協議,因此當代理服務器攔截到來自客戶端的Upgrade請求時,代理服務器需要將自己的Upgrade請求發送給后端服務器,包括適合的請求頭。
而且,由於WebSocket連接是長連接,與傳統的HTTP端連接截然不同,故反向代理服務器還需要允許這些連接處於打開(Open)狀態,而不能因為其空閑就關閉了連接。(https://blog.csdn.net/chszs/article/details/26369257)
歡迎關注作者微信公眾號