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

2021/12/3 7:10:17

本文主要是介绍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;
        }
    }
 
}


这篇关于Nginx反向代理WebSocket链接失败问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程