nodejs(express)搭建https服务器,给小程序做后台

1.准备https服务器(ssl证书)

一个由各大互联网公司赞助的免费https服务商:https://certbot.eff.org/

选择我的服务器:如ubuntu 16.04上运行nginx,会自动生成安装命令。like this:

nodejs(express)搭建https服务器,给小程序做后台_第1张图片

所有完成之后会给一段提示:

- Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/xxxxx.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/xxxxx.com/privkey.pem Your cert will expire on 2018-03-25.

To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew"

- Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal.

注意到期时间2018-03-25,在那之前续签即可:certbot renew

todo,这里等下写个脚本,或者配置别人写的:https://github.com/lukas2511/dehydrated

2.修改原来的服务,做个测试

上面生成的文件,能用到的是这两个:

/etc/letsencrypt/live/xxxxx.com/privkey.pem

/etc/letsencrypt/live/xxxxx.com/cert.pem

由于刚才生成是用的root账户,可能会出现权限问题,我就复制到我自己的项目目录/config/letsencrypt/里面,然后chown 到当前用户,如果没有r权限的话也要chmod一下

我的服务器使用的nodejs(express),使用pm2启动,ubuntu上配置nginx。

修改一下我的/bin/www启动文件:

******省略其他自带逻辑*****

var https = require('https');

var fs = require('fs');

const https_config = {

    key: fs.readFileSync('/home/panglong/geckoid/config/letsencrypt/privkey.pem'),

    cert: fs.readFileSync('/home/panglong/geckoid/config/letsencrypt/cert.pem')

} /** * Get port from environment and store in Express. */

var port = normalizePort(process.env.PORT || '3000');

app.set('port', port);

/** * Create HTTP server. */

var server = https.createServer(https_config,app);

******省略其他自带逻辑*****

这样配置完了就可以重启:

pm2 reload www(<--这是我的进程名字)

3.配置nginx

修改之前的nginx配置,这里第一步生成秘钥的时候,会做一些配置,这里只需要改动之前的业务逻辑到https即可:(别忘了重启:sudo nginx -s reload)

proxy_pass https://127.0.0.1:3000;

你可能感兴趣的:(nodejs(express)搭建https服务器,给小程序做后台)