有需求使用nginx反向代理websockt,因为webSocket协议是基于http协议的,因此可以使用nginx反向代理webSocket.
下面是具体的协议内容
Request URL: ws://x.x.x.x:8800/ Request Method: GET Status Code: 101 Switching Protocols request headers: Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Cache-Control: no-cache Connection: Upgrade Host: x.x.x.x:8800 Origin: http://www.websocket-test.com Pragma: no-cache Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits Sec-WebSocket-Key: M7CVPssrE5QD3UKq7pgeyA== Sec-WebSocket-Version: 13 Upgrade: websocket User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
对比可以发现关键的header是Connection更换为Upgrade
这里使用的nginx是centos7默认yum安装的,运行成功后可以直接修改默认的conf文件,路径是:/etc/nginx/nginx.conf
在配置文件最末添加具体代理websocket的配置:
upstream x.x.x.x_8800 { server x.x.x.x:8800; //这里配置的是被代理的websocket的ip及端口 } server { listen 8880; server_name 193.112.175.134; //这里配置是代理服务器的ip和端口 location / { proxy_pass http://x.x.x.x:8800; //这里配置的是被代理的websocket的ip及端口 proxy_http_version 1.1; //代理时使用的 http版本 //下列配置是重点内容 proxy_set_header Upgrade $http_upgrade;//把代理时http请求头的Upgrade 设置为原来http请求的请求头,wss协议的请求头为websocket proxy_set_header Connection "Upgrade";//http请求头的Connection设置为Upgrade proxy_set_header X-Real-IP $remote_addr;//代理设置原http请求的ip,填写$remote_addr 即可 proxy_set_header Host $host;//这里设置的是host,ws没做限制的话默认$host即可 proxy_set_header X-Forwarded-For $remote_addr;//这里没看懂,应该是用来识别请求ip的 } }
重启nginx后,测试ws成功
原创声明,本文系作者授权云+社区发表,未经许可,不得转载。
如有侵权,请联系 yunjia_community@tencent.com 删除。
我来说两句