温馨提示×

CentOS Node.js 如何配置 SSL 证书

小樊
44
2025-12-09 13:01:21
栏目: 云计算

在 CentOS 上配置 Node.js 应用的 SSL 证书,通常涉及以下几个步骤:

  1. 获取 SSL 证书

    • 你可以从证书颁发机构(CA)购买证书。
    • 如果你只是测试环境,可以使用 Let’s Encrypt 提供的免费证书。
  2. 安装 Node.js(如果尚未安装):

    sudo yum install nodejs npm
    
  3. 配置 Node.js 应用以使用 SSL: 假设你已经有一个 Node.js 应用,你需要在应用中配置 HTTPS 服务器。以下是一个简单的示例:

    const https = require('https');
    const fs = require('fs');
    const express = require('express');
    
    const app = express();
    
    // 读取 SSL 证书文件
    const options = {
      key: fs.readFileSync('/path/to/your/private.key', 'utf8'),
      cert: fs.readFileSync('/path/to/your/fullchain.pem', 'utf8')
    };
    
    // 创建 HTTPS 服务器
    https.createServer(options, app).listen(443, () => {
      console.log('HTTPS Server running on port 443');
    });
    
  4. 配置防火墙: 确保你的防火墙允许 HTTPS 流量(默认端口 443)。

    sudo firewall-cmd --permanent --zone=public --add-service=https
    sudo firewall-cmd --reload
    
  5. 重启 Node.js 应用: 保存你的配置文件并重启 Node.js 应用以应用更改。

    sudo systemctl restart your-nodejs-app
    

使用 Let’s Encrypt 获取免费证书

如果你使用 Let’s Encrypt 获取免费证书,可以使用 certbot 工具来自动化这个过程。以下是步骤:

  1. 安装 Certbot

    sudo yum install epel-release
    sudo yum install certbot python2-certbot-nginx
    
  2. 获取证书

    sudo certbot --nginx -d yourdomain.com
    

    这将自动配置 Nginx 并获取证书。如果你使用的是 Node.js 应用而不是 Nginx,你可以使用 certbot 的 HTTP-01 挑战来验证域名所有权。

  3. 配置 Node.js 应用以使用证书: 按照上面的步骤配置你的 Node.js 应用以使用 Let’s Encrypt 提供的证书。

注意事项

  • 确保你的私钥文件(private.key)和证书文件(fullchain.pem)的安全性。
  • 定期更新你的证书,因为 Let’s Encrypt 证书通常有效期为 90 天。
  • 如果你使用的是反向代理(如 Nginx),确保正确配置代理设置,以便 Node.js 应用能够处理 HTTPS 请求。

通过以上步骤,你应该能够在 CentOS 上成功配置 Node.js 应用的 SSL 证书。

0