http https ws wss 的区别,因为小程序只能使用https 所以它的websoket 只能使用wss 协议
http -> new WebSocket(‘ws://xxx’) 一般使用 80端口
https -> new WebSocket(‘wss://xxx’)一般使用443 端口
http://img.520haigo.com
ws://img.520haigo.com/wss
https://img.520haigo.com
wss:///img.520haigo.com/wss
nginx 搭建出小程序所使用的https和wss共存 nginx配置如下
这些配置放到一个nginx配置下面就可以 例如: conf.d/img.520haigo.com.conf文件中的配置 如果使用阿里云服务器需要安全组中开启9501端口
upstream websocket{ //监听 你的后端soket的端口 我用的swoole9501
server 127.0.0.1:9501 fail_timeout=0;
}
server{ //这里是http 转发到 https协议,适用于网页端 例子就是www.baidu.com 301 跳转操作
listen 80;
server_name img.520haigo.com;
location / {
if ($request_method ~ ^(POST|DELETE|OPTIONS)$) {
proxy_pass https://img.520haigo.com;
break ;
}
rewrite ^/(.*)$ https://img.520haigo.com/$1 permanent;
}
}
server{
listen 443 ssl;
server_name img.520haigo.com;
index index.html index.htm index.php;
root /alidata/www/doodoo/blog/public;
#ssl on;
ssl_certificate /alidata/server/nginx-1.7.9/2471666_img.520abc.com.pem; //你的证书地址
ssl_certificate_key /alidata/server/nginx-1.7.9/2471666_img.520abc.com.key; //你的证书地址
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
location /wss{ //这里是websoket的转发操作,如果访问 wss://....../wss 就会进入到这里转发到后端的ws协议
proxy_pass http://websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_read_timeout 600;
}
location / {
try_files $uri $uri/ /index.php?$query_string; //laravel 框架必须配置的文件重写操作
}
location ~ .*\.(php|php5)?$
{
#fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_pass 127.0.0.1:9000; //监听的php端口
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 1h;
}
}
上面的配置适用于: http => 301 跳转https && https=>wss
https 证书的话直接去阿里云申请免费的DV证书就可以
注意: 笔者在上面的配置这里踩过坑 ,https跳转wss协议 最主要的配置有三个 如下
proxy_http_version 1.1; //告诉nginx 使用http1.1 长连接协议 http 默认是1.0的
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “Upgrade”;//告诉nginx 使用http的升级版,并会在http头信息中添加websoket 的信息
如果 proxy_http_version 1.1 没有设置,会出现wx.connectSocket 出现连接成功
但是wx.onSocketOpen 不会出现成功,发送消息也会失败,提示soket连接失败
注意:笔者配置的时候遇到了 配置 proxy_http_version nginx 启动报错
遇到这个问题,我选择了重装nginx 之前是 1.7.2 后来重装的nginx-1.8.2
注意:nginx 在60秒内没有消息接收的话,会自动断开连接 proxy_read_timeout 600; 设置nginx监听时常 改为600 秒但也不是长久之计,socket还需要添加 心跳检测才行呀!!!
前端访问 wss://img.520haigo.com/wss
注意啦:nginx 里面配置的是 /wss 所以域名里面 wss后边切不可加/ , wss/ 这样的话会返回301