linux

Linux Node.js如何配置SSL证书

小樊
38
2025-04-17 15:26:09
栏目: 云计算

在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!');
});

// 读取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('Server running on https://yourdomain.com:443');
});

3. 自动续期证书

Let’s Encrypt证书有效期为90天,因此需要自动续期。Certbot可以自动处理续期过程。

设置自动续期

编辑Certbot的续期配置文件:

sudo nano /etc/letsencrypt/renewal-hooks/deploy/post.sh

添加以下内容:

#!/bin/bash

# 重启Node.js应用程序
systemctl restart your-nodejs-app

确保脚本有执行权限:

sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/post.sh

然后,编辑Certbot的续期配置文件:

sudo nano /etc/letsencrypt/renewal-hooks/deploy/install-post.sh

添加以下内容:

#!/bin/bash

# 启动Node.js应用程序
systemctl start your-nodejs-app

确保脚本有执行权限:

sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/install-post.sh

4. 使用Nginx作为反向代理

为了更好地管理SSL证书和负载均衡,你可以使用Nginx作为反向代理。

安装Nginx

sudo apt update
sudo apt install nginx

配置Nginx

编辑Nginx配置文件:

sudo nano /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;

    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连接。

curl -I https://yourdomain.com

如果一切正常,你应该会看到HTTP状态码200和SSL证书信息。

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

0
看了该问题的人还看了