当前位置: 首页 > 帮助中心

Ubuntu Node.js如何配置SSL证书

时间:2026-01-30 11:32:08

在Ubuntu上为Node.js应用程序配置SSL证书,可以按照以下步骤进行:

1. 获取SSL证书

首先,你需要一个SSL证书。你可以从以下几种方式获取:

Let’s Encrypt:免费且自动化的证书颁发机构。购买证书:从商业证书颁发机构购买。使用Let’s Encrypt获取证书

你可以使用certbot工具来获取和续订Let’s Encrypt证书。

    安装certbot

    sudo apt updatesudo apt install certbot python3-certbot-nginx

    获取证书:

    sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

    按照提示完成证书的获取和配置。

2. 配置Nginx反向代理

如果你使用Nginx作为反向代理,可以在Nginx配置文件中设置SSL。

    编辑Nginx配置文件:

    sudo nano /etc/nginx/sites-available/yourdomain.com

    添加或修改以下配置:

    server {listen 80;server_name yourdomain.com www.yourdomain.com;return 301 https://$host$request_uri;}server {listen 443 ssl;server_name yourdomain.com www.yourdomain.com;ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;ssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers HIGH:!aNULL:!MD5;location / {proxy_pass http://localhost:3000; # 你的Node.js应用监听的端口proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;}}

    启用配置:

    sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/sudo nginx -tsudo systemctl restart nginx
3. 配置Node.js应用

如果你的Node.js应用直接监听443端口,你需要修改应用的配置。

    修改Node.js应用的监听端口(例如,改为3000):
    const express = require('express');const app = express();const https = require('https');const fs = require('fs');const options = {key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem'),cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem')};app.get('/', (req, res) => {res.send('Hello World!');});https.createServer(options, app).listen(3000, () => {console.log('Server running on https://yourdomain.com:3000');});
4. 自动续订证书

Let’s Encrypt证书每90天需要续订一次。你可以使用certbot的自动续订功能。

    编辑/etc/letsencrypt/renewal-hooks/deploy/renewal.sh文件,添加以下内容:

    systemctl reload nginx

    设置定时任务:

    sudo crontab -e

    添加以下行:

    0 0,12 * * * root certbot renew --post-hook "systemctl reload nginx"

通过以上步骤,你可以在Ubuntu上为Node.js应用程序配置SSL证书,并确保证书能够自动续订。


上一篇:如何优化Debian VirtualBox虚拟机启动速度
下一篇:如何使用OpenSSL在Linux上实现数据备份与恢复
Ubuntu
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器
  • 英特尔第五代 Xeon CPU 来了:详细信息和行业反应
  • 由于云计算放缓引发扩张担忧,甲骨文股价暴跌
  • Web开发状况报告详细介绍可组合架构的优点
  • 如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳
  • 美光在数据中心需求增长后给出了强有力的预测
  • 2027服务器市场价值将接近1960亿美元
  • 生成式人工智能的下一步是什么?
  • 分享在外部存储上安装Ubuntu的5种方法技巧
  • 全球数据中心发展的关键考虑因素
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器

    英特尔第五代 Xeon CPU 来了:详细信息和行业反应

    由于云计算放缓引发扩张担忧,甲骨文股价暴跌

    Web开发状况报告详细介绍可组合架构的优点

    如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳

    美光在数据中心需求增长后给出了强有力的预测

    2027服务器市场价值将接近1960亿美元

    生成式人工智能的下一步是什么?

    分享在外部存储上安装Ubuntu的5种方法技巧

    全球数据中心发展的关键考虑因素