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;
        }
    }
 
}
上一篇:SocketException: Connection or inbound has closed


下一篇:jdbc-使用java连接mysql