本人在近段时间接触到一个websocket项目的时候,在windows上运行一切正常,但迁移到liunx上用nginx反向代理的时候,各种坑,握手失败报这种错误:WebSocket connection to 'ws://192.168.16.20:8083/chat' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT,也参考了百度上很多种方法,没有起啥作用,无奈只得翻墙去谷歌,终于找到了一篇靠谱的文章解决了我的问题:

nginx配置图如下:

nginx反向代理websocket

配置代码:

location /chat {
           proxy_pass http://192.168.16.20:8083/chat;
           proxy_http_version 1.1;
           proxy_set_header  X-Real-IP  $remote_addr;
           add_header Access-Control-Allow-Origin *;                                                                                                                                                                       
           proxy_set_header Upgrade websocket;
           proxy_set_header Connection Upgrade;
           proxy_set_header Host $host;
           proxy_set_header X-Real-IP $remote_addr;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           rewrite /chat/(.*) /$1 break;
        }

相关文章: