HTTPS站点使用WebSocket的常见错误及解决方案

因为HTTPS是基于SSL依靠证书来验证服务器的身份,并为浏览器和服务器之间的通信加密,所以在HTTPS站点调用某些非SSL验证的资源时浏览器可能会阻止。比如使用ws://***调用websocket服务器或者引入类似http://***.js的js文件等都会报错。这里简述一下连接websocket服务器时的错误及解决方案。当使用ws://连接websocket服务器时会出现类似如下错误:

Mixed Content: The page at '*****' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://*****'. This request has been blocked; this endpoint must be available over WSS.
(anonymous) 
Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.

如果浏览器不阻止,那在https站点下调用ssl资源才可以,面说一下解决方案:

我的HTTPS站点使用Nginx服务器,其他服务器也是类似的思路,可以用服务器代理ws服务,可以用nginx的WebSocket proxying,简述一下配置方案

若不设置proxy_read_timeout这个,默认没有返回1分钟后自动断开链接。

以下为Nginx配置

server {
	     listen 80 default backlog=2048;
		 listen 443 ssl;
		 server_name www.您的域名.com;
		 #ssl on;       
		 root html;
		 index index.html index.htm;
		 ssl_certificate   cert/3264264_www.您的域名.com.pem;
		 ssl_certificate_key  cert/3264264_www.您的域名.com.key;
		 ssl_session_timeout 5m;
		 ssl_session_cache shared:SSL:50m;
		 ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
		 ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
		 ssl_prefer_server_ciphers on;
		 if ($server_port = 80 ) {
				 return 301 https://www.您的域名.com$request_uri;
				 
        }

		 location / {
			 root /var/www/kayu-sc-web/dist; 
			 index index.html index.htm;
			  if (!-e $request_filename) {
				rewrite ^/(.*) /index.html last;
				break;
			}
		 }
		 
	#webSocket wws 加密链接
	location /wss
	  {
		proxy_pass http://127.0.0.1:webSocket端口号/webSocket/;
		proxy_http_version 1.1;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection "Upgrade";
		proxy_set_header X-Real-IP $remote_addr;
		proxy_read_timeout 600s;#链接时间,超时自动断开链接
	  }


		#让http请求重定向到https请求
        error_page 497  https://$host$request_uri;
		}

前端配置如下:

 this.websock = new WebSocket('wss://www.您的域名.com/wss/' + this.id);
 this.websock.onmessage = this.websocketonmessage;
 this.websock.onopen = this.websocketonopen;
 this.websock.onerror = this.websocketonerror;
 this.websock.onclose = this.websocketclose;

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值