配置如下:

http { map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { ... location /chat/ { proxy_pass http://backend; proxy_http_version 1.1; #以下配置添加代理头部: proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } }

实验案例:

配置websockeet做事器,客户端通过代理连接做事器端。
环境如下:

websocketphpwssnginx署理websocket设置装备摆设 Docker

websocket做事端:192.168.1.110:8010

nginx :192.168.1.131:8081

1:利用nodejs实现一个websocket做事端,监听8010端口,等待websocket链接。

安装nodejs与npm,并安装ws模块。
(这里通过官网程序包实现)

[root@192_168_1_110 ~]# tar -zxvf node-v6.2.0-linux-x64.tar.gz[root@192_168_1_110 ~]# ln -s /root/node-v6.2.0-linux-x64/bin/node /usr/local/bin/node[root@192_168_1_110 ~]# ln -s /root/node-v6.2.0-linux-x64/bin/node /usr/local/bin/node[root@192_168_1_110 ~]# npm install -g ws[root@192_168_1_110 ~]# npm install -g wscat

编写websocket做事监听程序:

[root@192_168_1_110 ~]# vim server.jsconsole.log(\公众Server started\公众);var Msg = '';var WebSocketServer = require('ws').Server, wss = new WebSocketServer({port: 8010});wss.on('connection', function(ws) {ws.on('message', function(message) {console.log('Received from client: %s', message);ws.send('Server received from client: ' + message);});});

启动websocket做事端:

[root@192_168_1_110 ~]# node server.jsServer started

重新开启一个终端,利用wscat程序测试程序连接:

[root@192_168_1_110 ~]# /root/node-v6.2.0-linux-x64/lib/node_modules/wscat/bin/wscat --connect ws://192.168.1.110:8010connected (press CTRL+C to quit)> This is a websocket test...< Server received from client: This is a websocket test...>

查看做事端:

[root@192_168_1_110 ~]#node server.jsServer startedReceived from client: This is a websocket test... ----从客户端吸收到的信息

至此,websocket环境搭建完成。

2:配置nginx,代理110上的websocket链接。

[root@192_168_1_131 ~]# vim /opt/conf/nginx/nginx.conf......http {......map $http_upgrade $connection_upgrade {default upgrade;'' close;}.......include vhost/.conf; [root@192_168_1_131 ~]# vim /opt/conf/nginx/vhost/nodejs.confupstream nodejs{server 192.168.1.110:8010;}server {listen 8010;access_log /opt/logs/nginx/nodejs.log main;location / {proxy_pass http://nodejs;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection $connection_upgrade;}}

重新加载nginx配置:

[root@192_168_1_131 ~]# service nginx reload

这样配置过后,在nginx做事器上访问8010端口的要求,将会全部发送到后端192.168.1.110的8081端口上。

3:验证websocket要求代理:(把ws地址指向192.168.1.131:8010)

[root@192_168_1_110 ~]# /root/node-v6.2.0-linux-x64/lib/node_modules/wscat/bin/wscat --connect ws://192.168.1.131:8010connected (press CTRL+C to quit)> This is a websocket test through nginx proxying...< Server received from client: This is a websocket test through nginx proxying...>

查看做事端:

[root@192_168_1_110 ~]#node server.jsServer startedReceived from client: This is a websocket test...Received from client: This is a websocket test through nginx proxying...

可以看到通过代理,websocket也能正常吸收到客户真个要求信息。

本文转载地址:http://blog.51cto.com/icenycmh/1839566

作者icenycmh的原创作品