前端如何给自己的node.js后台服务配置免费的SSL?

1,213 阅读3分钟

接前文,上个月已经部署到了服务器,因为搬家牙齿正畸还有工作压力一直摆烂了2个月,啥也没做。但我还是想要把之前花钱买的云服务器利用起来,同时也想让自己做的小程序上线。

之前已经部署好了express.js后端,域名也已经备案了。最后一步就是配置一下SSL,同样我还是不想安装宝塔面板,毕竟就是一个小服务器,不想装这些东西浪费性能了,就辛苦自己多多gpt一下了。

想使用免费的SSL,最简单的办法就是使用let's encrypt的certbot + Nginx做反向代理。所以总共就3步:1.安装nginx,2.安装certbot 3.反向代理。

安装nginx

所以接下来,先安装一下nginx:

sudo apt update # 更新软件包
sudo apt install nginx # 安装nginx
sudo systemctl status nginx # 安装后默认就会自动运行,这一行是用来查看运行状态

如果出现启动报错的情况,多半是80端口已经被占用了。

image.png

找到是哪个程序占用了端口后,再重新启动ngnix就可以了

sudo systemctl restart nginx # 重启
sudo systemctl status nginx # 查看状态

# 一些常见的命令
vim /etc/nginx/nginx.conf # 编辑配置文件
nginx -s stop # fast shutdow
nginx -s quit # graceful shutdown
nginx -s reload # changing configuration, starting new worker processes with a new configuration, graceful shutdown of old worker processes
nginx -s reopen # re-opening log files

安装并运行certbot

直接照着certbot教程来搞就好了,我就不复制粘贴了,没有必要。这里选择运行在nginx上,然后选择一下运行在哪个操作系统。

它有一行命令sudo certbot --nginx直接能把ssl的配置写到nginx配置里面,这样避免自己复制粘贴搞错。

然后我就能立即通过https访问我的网站了:

image.png

运行它的教程中的最后一行命令sudo certbot renew --dry-run前,记得先把nginx停一下,因为nignx运行的时候占用了80端口,先执行上面的命令,让它自动续签的定时任务跑起来来了,再重新运行nginx。

配置反向代理

通过问new bing,发现certbot是自动将ssl配置写入到了/etc/nginx/sites-available/default下,所以我们先将该文件备份一下,以免搞砸了。

image.png

cd /etc/nginx/
mkdir backup # 创建一个备份配置的文件夹
cp ./sites-available/default ./backup #将sites-available文件夹下的default文件复制到backup文件夹下

因为我的node.js 服务运行在端口4000,所以我的nginx配置需要实现:

  1. 反向代理端口4000
  2. 如果访问的是80端口,则重定向443端口,并开启 SSL 加密。

这里假设我的网站域名是example.org,certbot已经在443端口这个server块帮我做了SSl加密。

我要做的就是用户访问80端口的时候重定向到443端口,而且访问根路径 / 的请求会被代理到 http://localhost:4000

server {
  listen 80 ;
  listen [::]:80 ;
  root /var/www/html;
  index index.html index.htm index.nginx-debian.html;
  return 301 https://$host$request_uri;
}

server {

  root /var/www/html;
  index index.html index.htm index.nginx-debian.html;
  server_name example.org; # managed by Certbot

  location / {
    proxy_pass http://localhost:4000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  listen [::]:443 ssl ipv6only=on; # managed by Certbot
  listen 443 ssl; # managed by Certbot
  ssl_certificate /etc/letsencrypt/live/example.org/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/example.org/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

短短20多行配置就终于看到了https!因为我的小破网站没有做任何权限校验,所以我就给域名打个马赛克,以防万一。

image.png