ubuntu

Ubuntu Node.js如何配置SSL证书

小樊
43
2025-07-01 17:19:38
栏目: 云计算

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

1. 获取SSL证书

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

使用Let’s Encrypt获取证书

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

  1. 安装certbot

    sudo apt update
    sudo apt install certbot python3-certbot-nginx
    
  2. 获取证书:

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

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

2. 配置Nginx反向代理

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

  1. 编辑Nginx配置文件:

    sudo nano /etc/nginx/sites-available/yourdomain.com
    
  2. 添加或修改以下配置:

    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;
        }
    }
    
  3. 启用配置:

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

3. 配置Node.js应用

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

  1. 修改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的自动续订功能。

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

    systemctl reload nginx
    
  2. 设置定时任务:

    sudo crontab -e
    

    添加以下行:

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

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

0
看了该问题的人还看了