使用nginx进行websocket的ws和wss的反向代理
代理是成功的, 但是并没有成功的升级成 websocket 长连接
客户端进行握手的时候,上游服务器返回的数据nginx没有通过长连接实时返回给客户端,而是在上游服务器关闭连接或者超时后,nginx才将数据返回给客户端。
nginx版本1.18.0 -------- 这是nginx代理ws和wss的配置
http
{
#include /nginx/conf/naxsi_core.rules;
include mime.types;
default_type application/octet-stream;
#access_log logs/access.log main;
access_log off;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket {
server 192.168.1.58:13527;
keepalive 512;
}
server {
listen 80;
listen 443;
server_name wss.com;
charset utf-8;
ssl on; # 启用ssl功能
ssl_certificate /test/test.crt;
ssl_certificate_key /test/test.key;
ssl_session_timeout 5m;
ssl_session_cache shared:SSL:50m;
ssl_protocols SSLv3 SSLv2 TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
ssl_prefer_server_ciphers on;
ssl_verify_client off;
add_header Cache-Control no-store;
keepalive_timeout 3600s;
keepalive_requests 10000000;
proxy_http_version 1.1;
if ($request_method = 'OPTIONS') {
return 204;
}
location /wss
{
proxy_redirect off;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real_IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr:$remote_port;
proxy_set_header X-Forwarded-Host $Server_name;
proxy_set_header X-NginX-Proxy true;
proxy_connect_timeout 12000s;
proxy_read_timeout 36000s;
proxy_send_timeout 36000s;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
# proxy_buffering off;
proxy_pass http://websocket/;
}
}
}
nginx的error.log里面提示:
2020/12/09 10:24:43 [error] 8048#8724: *5 upstream sent no valid HTTP/1.0 header while reading response header from upstream, client: 192.168.1.58, server: wss.com, request: "GET /wss HTTP/1.1", upstream: "http://192.168.1.58:13527/", host: "wss.com"
握手成功的数据是在连接被关闭以后nginx才返回的
被这个问题弄得头都大了,没有有人遇到过这个问题呢,是怎么决绝的啊
看你error日志应该和后端的服务有关,我们是这样配置的,你参考一下 websocket技术,websocket的反向代理实现比较特殊,具体配置如下:
在nginx的主配置文件的http段的作用域中添加以下配置:
#vim /etc/nginx/nginx.conf
map $http_upgrade $connection_upgrade { default upgrade; '' close; }
编写websocket的反向代理设置
#vim /etc/nginx/conf.d/k2wrapper.conf
upstream k2wrapperserver { hash $remote_addr consistent; server 192.168.6.50:31002; server 192.168.6.51:31002; }
server { listen 8182; server_name xxxxxxxx.cn;
location / { proxy_pass http://k2wrapperserver/; proxy_set_header Host $host:$server_port; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。