阿里云nodejs开https服务(koa2+nginx)
1.koa 添加https配置
在已完成脚手架搭建后 安装koa-sslify模块
cnpm install koa-sslify --save
app.js内使用sslify
const sslify = require('koa-sslify').default
app.use(sslify())
在www文件里添加https服务
var https = require('https');
var options = {
key: fs.readFileSync('./ssl/www.XXXXX.XXX.key'), //ssl文件路径 第一步下载下来的证书文件
cert: fs.readFileSync('./ssl/www.XXXXX.XXX.pem') //ssl文件路径 第一步下载下来的证书文件
};
var port = normalizePort(process.env.PORT || '10000');//端口使用10000以上的端口 443阿里云盾在用 所以要用nginx转发
var httpsServer = https.createServer(options, app.callback());//参照原有http服务的server 添加 httpsServer监听和事件
2.nginx 添加https配置
先看当前nginx有没安装ssl模块
有OpenSSL代表已装,未装则进入nginx源码文件夹
跑下面命令安装ssl模块
./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
安装模块完成后跑 make 编译 没问题 make install 安装(已有nginx配置的先保存下conf,安装后覆盖原有配置)
make
make install
确认ssl模块没问题后 在nginx的 conf文件中添加 https配置
server {
listen 443 ssl;
server_name XXXXX.XXXXX.XXXXX;#需要https的域名
ssl_certificate "/usr/local/nginx/conf/ssl/xxxx.xxxx.xxxx.pem";#证书位置 证书可以在阿里云免费申请 证书类型有多个 只有部分类型可以免费
ssl_certificate_key "/usr/local/nginx/conf/ssl/xxxx.xxxx.xxxx.key";#证书位置
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
#443端口 /aaa 路径下请求转发到 koa2在10000端口的服务
location /aaa {
proxy_pass https://127.0.0.1:10000/bbb;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#443端口 /ccc 转发到 其它站点
location /ccc {
proxy_pass https://eee.eee.eee/ddd;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
include vhost/*.conf;#导入vhost文件夹下的其它配置 个人
}
3.阿里云主机防火墙配置
先在安全组里添加 443端口
然后进入主机使用命令防火墙开启443端口
irewall-cmd --zone=public --add-port=443/tcp --permanent
提示success后,重启防火墙,如果失败百度对应错误提示解决
firewall-cmd --reload
重启成功后把koa服务和nginx都重启一下 就可以使用https访问对应域名了