nginx配置websocket

问题

最近开发的时候需要用到websocket像前端推送消息,本地测试正常,但是部署到服务器上之后连接失败

3.0746436a626b95efe66f.js:1 WebSocket connection to 'ws://***.***.***.***:8066/****' failed: Error during WebSocket handshake: Unexpected response code: 200

和度娘研究后发现,原因是我们服务器上用的是nginx代理,然后查看nginx配置后发现,并没有对websocket进行配置

解决方法

原配置:

location ~ /(api)/.* {
                        proxy_next_upstream http_502 http_504 error timeout invalid_header;
                        proxy_set_header Host $host:$server_port;
                        proxy_set_header X-Forwarded-For $remote_addr;
                        proxy_pass http://testTomcat;
                        #expires 1d;
        }

修改后的配置:

location ~ /(api)/.* {
                        proxy_next_upstream http_502 http_504 error timeout invalid_header;
                        proxy_set_header Host $host:$server_port;
    					# websocket的配置
                        proxy_http_version 1.1;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection "upgrade";
    					#
                        proxy_set_header X-Forwarded-For $remote_addr;
                        proxy_pass http://testTomcat;
                        #expires 1d;
        }

修改后重启nginx,完美解决~

遇到的坑

中间测试了多种修改方法,如:

location ~ /(api)/.* {
    proxy_pass http://testTomcat;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

location ~ /(api)/.* {
    proxy_next_upstream http_502 http_504 error timeout invalid_header;
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_pass http://testTomcat;
    #expires 1d;
}

如果直接添加一个location,发现原来能访问的接口也会出现问题,这应该是配置冲突的原因吧

posted @ 2020-08-10 15:13  xy7053  阅读(875)  评论(0编辑  收藏  举报