ubuntu20.04 使用nginx代理https转发http及微信小程序wss转发ws请求连接webSocket
最近开发小程序使用到websocket连接,发现部署发布上线后ws连接方式不行,不想修改原有代码,所以使用了Nginx做了代理转发,将wss请求转发为ws的方式连接
小程序上线后访问的方式必须为https和wss:
使用https或wss必须要求:
- 域名备案
- 使用证书ssl
1.安装Nigix
安装教程:javascript:void(0)
2.编辑Nginx配置文件
下载好证书,笔者的证书是腾讯云提供的免费的
ubuntu下路径:/etc/nginx/nginx.conf
编辑nginx.conf
文件:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 443;
ssl on;
ssl_certificate ***.crt; #你的上传到服务器的证书位置
ssl_certificate_key ***.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;
location /wss {
proxy_pass http://127.0.0.1:8899; # 使用地址wss://your.server.com/wss 访问会转发到此服务器的该地址http://127.0.0.1:8899
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-Real-IP $remote_addr;
}
location / {
proxy_pass http://127.0.0.1:8877;#使用地址https://your.server.com 访问会转发到此服务器的该地址http://127.0.0.1:8877
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header Access-Control-Allow-Origin *;#跨域访问设置
}
}
}
3.小程序测试代码
wx.connectSocket({
url: 'wss://your.servername.com/wss'
});
wx.onSocketOpen(function(res) {
console.info('websocket连接成功');
});
wx.onSocketClose(function(res) {
console.log('WebSocket 已关闭!')
});
wx.onSocketError(function(res){
console.log('WebSocket连接打开失败,请检查!')
});
wx.onSocketMessage(function(res) {
console.log('收到服务器内容:' + res.data)
})
4.web端代码测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>otis elevator server</title>
<script type="text/javascript" src="../static/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../static/js/index.js"></script>
</head>
<body>
<script type="text/javascript">
$(function () {
console.log('ws-----------------')
// 证书是会检查域名的,请使用域名连接
// ws = new WebSocket("ws://apps.jiaxi.space:8899");
ws = new WebSocket("wss://your.servername.com/wss");
ws.onopen = function () {
console.log("连接成功");
ws.send(JSON.stringify({'hello':'tom'}));
console.log("给服务端发送一个字符串:tom");
};
ws.onmessage = function (e) {
console.log("收到服务端的消息:" + e.data);
};
})
console.log('index-----------------')
</script>
</body>
</html>
done!
如能帮助到你,欢迎留言点赞加关注!3Q!