因为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;