centos

如何在 CentOS 上为 Node.js 应用添加 SSL 证书

小樊
97
2025-02-12 06:53:18
栏目: 云计算
亿速云ssl证书,防植入防监听防窃取! 查看>>

在 CentOS 上为 Node.js 应用添加 SSL 证书,可以按照以下步骤进行操作:

1. 获取 SSL 证书

首先,你需要获取一个 SSL 证书。你可以从 Let’s Encrypt 免费获取证书,或者购买一个商业证书。

使用 Let’s Encrypt 获取证书

  1. 安装 Certbot:

    sudo yum install epel-release
    sudo yum install certbot python2-certbot-nginx
    
  2. 运行 Certbot 获取证书:

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

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

2. 配置 Nginx 反向代理

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

  1. 编辑 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf):

    server {
        listen 80;
        server_name yourdomain.com www.yourdomain.com;
    
        location /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }
    
        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;
        }
    }
    
  2. 重新加载 Nginx 配置:

    sudo systemctl reload nginx
    

3. 配置 Node.js 应用

确保你的 Node.js 应用监听在正确的端口上(例如 3000),并且能够处理 HTTPS 请求。

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

const app = express();

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

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(3000, () => {
    console.log('Server is running on https://yourdomain.com:3000');
});

4. 测试 SSL 配置

打开浏览器,访问 https://yourdomain.com,你应该能够看到你的 Node.js 应用,并且浏览器地址栏会显示安全锁图标,表示 SSL 配置成功。

5. 自动续期证书

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

  1. 编辑 Certbot 的续期脚本:

    sudo crontab -e
    
  2. 添加以下行以每天检查并续期证书:

    0 0 * * * certbot renew --post-hook "systemctl reload nginx"
    

通过以上步骤,你就可以在 CentOS 上为 Node.js 应用成功添加 SSL 证书了。

亿速云提供多种品牌、不同类型SSL证书签发服务,包含:域名型、企业型、企业型专业版、增强型以及增强型专业版,单域名SSL证书300元/年起。点击查看>>

相关推荐:如何在CentOS上配置Node.js反向代理

0
看了该问题的人还看了