网络知识
如何在CentOS上配置Node.js的SSL证书
2025-07-06 13:49  点击:0

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

    获取SSL证书:

    你可以从Let’s Encrypt免费获取SSL证书。使用Certbot工具来获取和续订证书。

    安装Certbot:

    sudo yum install epel-releasesudo yum install certbot python2-certbot-nginx

    获取证书:

    假设你的域名是example.com,运行以下命令:
    sudo certbot --nginx -d example.com -d www.example.com
    Certbot会自动配置Nginx并获取证书。

    配置Node.js应用程序:

    确保你的Node.js应用程序监听443端口(HTTPS默认端口)。你可以使用http模块来创建一个简单的HTTPS服务器:
    const https = require('https');const fs = require('fs');const express = require('express');const app = express();// 读取SSL证书文件const options = {key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),cert: fs.readFileSync('/etc/letsencrypt/live/example.com/fullchain.pem')};// 创建HTTPS服务器https.createServer(options, app).listen(443, () => {console.log('HTTPS Server running on port 443');});

    重定向HTTP到HTTPS:

    如果你使用Nginx作为反向代理,可以在Nginx配置中添加重定向规则:
    server {listen 80;server_name example.com www.example.com;location / {return 301 https://$host$request_uri;}}

    测试配置:

    确保你的Node.js应用程序和Nginx配置正确无误。使用浏览器访问你的域名,检查是否显示安全连接。

    自动续订证书:

    Certbot会自动设置一个cron任务来定期续订证书。你可以手动测试续订过程:
    sudo certbot renew --dry-run

通过以上步骤,你可以在CentOS上成功配置Node.js应用程序的SSL证书。确保定期检查和更新证书,以保持安全性。