如何在 Linux 上为 Node.js 配置 SSL 证书

182
2025/4/9 15:32:58
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在 Linux 上为 Node.js 配置 SSL 证书,可以按照以下步骤进行操作:

1. 获取 SSL 证书

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

  • Let’s Encrypt:提供免费的 SSL 证书。
  • 购买证书:从证书颁发机构(CA)购买。
  • 自签名证书:适用于测试环境。

使用 Let’s Encrypt 获取证书

你可以使用 certbot 工具来获取 Let’s Encrypt 证书。以下是安装和使用 certbot 的步骤:

# 安装 certbot 和 certbot-apache(如果你使用的是 Apache)
sudo apt update
sudo apt install certbot python3-certbot-apache

# 运行 certbot 获取证书
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

2. 配置 Node.js 应用以使用 SSL 证书

假设你已经有一个 Node.js 应用,并且你希望它使用 SSL 证书。你可以使用 https 模块来创建一个 HTTPS 服务器。

示例代码

const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();

// 读取 SSL 证书和私钥文件
const options = {
  key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem', 'utf8'),
  cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem', 'utf8')
};

// 创建 HTTPS 服务器
https.createServer(options, app).listen(443, () => {
  console.log('HTTPS Server running on port 443');
});

3. 自动续期 Let’s Encrypt 证书

Let’s Encrypt 证书通常有效期为 90 天,因此你需要设置自动续期。certbot 提供了自动续期的功能。

# 设置自动续期
sudo crontab -e

# 添加以下行以每天检查一次续期
0 0 * * * /usr/bin/certbot renew --post-hook "systemctl reload nginx"

4. 配置反向代理(可选)

如果你使用的是 Nginx 或 Apache 作为反向代理,你可以配置它们来转发请求到你的 Node.js 应用,并使用 SSL 证书。

Nginx 配置示例

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;

    location / {
        proxy_pass http://localhost:3000;
        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;
    }
}

Apache 配置示例

<VirtualHost *:443>
    ServerName yourdomain.com www.yourdomain.com

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem

    ProxyPass / http://localhost:3000/
    ProxyPassReverse / http://localhost:3000/
</VirtualHost>

5. 重启服务

最后,重启你的 Node.js 应用和反向代理服务以应用更改。

# 重启 Node.js 应用
sudo systemctl restart your-node-app

# 重启 Nginx 或 Apache
sudo systemctl restart nginx
# 或者
sudo systemctl restart apache2

通过以上步骤,你就可以在 Linux 上为 Node.js 配置 SSL 证书,并确保你的应用通过 HTTPS 提供服务。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: linux issue文件的版本信息