linux

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

小樊
42
2025-07-17 16:02:06
栏目: 云计算

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

1. 获取SSL证书

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

使用Let’s Encrypt获取证书

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

# 安装certbot
sudo apt update
sudo apt install certbot

# 获取证书
sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com

2. 配置Node.js应用程序

假设你已经有一个Node.js应用程序,你可以使用https模块来配置SSL。

示例代码

创建一个简单的Node.js应用程序并配置SSL:

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

const app = express();

app.get('/', (req, res) => {
  res.send('Hello, SSL!');
});

const options = {
  key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem'),
  cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem')
};

https.createServer(options, app).listen(443, () => {
  console.log('Server running on https://yourdomain.com:443');
});

3. 自动续期证书

Let’s Encrypt的证书有效期为90天,因此你需要设置自动续期。

设置自动续期

你可以使用certbot的自动续期功能:

sudo certbot renew --post-hook "systemctl reload nginx"

如果你使用的是Nginx作为反向代理,可以在/etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh中添加以下内容:

#!/bin/bash
systemctl reload nginx

然后确保脚本有执行权限:

chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh

4. 使用Nginx作为反向代理

为了更好地管理SSL和负载均衡,通常会使用Nginx作为反向代理。

安装Nginx

sudo apt update
sudo apt install nginx

配置Nginx

编辑Nginx配置文件(例如/etc/nginx/sites-available/yourdomain.com):

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        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 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;

    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;
    }
}

启用配置:

sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

5. 测试配置

确保一切配置正确后,你可以通过浏览器访问https://yourdomain.com,应该会看到你的Node.js应用程序,并且浏览器地址栏会显示安全锁标志。

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

0
看了该问题的人还看了