开发者社区> 问答> 正文

nginx反向代理ws和wss出现问题

使用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才返回的

image.png

被这个问题弄得头都大了,没有有人遇到过这个问题呢,是怎么决绝的啊

展开
收起
成长中的技术人员 2020-12-09 10:49:41 3238 0
1 条回答
写回答
取消 提交回答
  • 看你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"; } }

    #使用阿里云的你竟然还不知道这个?#

    2020-12-11 14:01:39
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
《Nginx 代理系统常用手册》 立即下载
CentOS Nginx PHP JAVA 多语言镜像使用手 立即下载
CentOS Nginx PHP JAVA多语言镜像使用手册 立即下载