Nginx反向代理WebSocket链接失败问题

问题记录:本地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

 欢迎关注作者微信公众号

原文地址:https://www.cnblogs.com/zhanqing/p/15632843.html