网络知识
Node.js在Linux如何配置SSL证书
2025-07-20 08:52  点击:0

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

    获取SSL证书首先,你需要获得一个SSL证书。你可以从证书颁发机构(CA)购买,或者使用免费的Let’s Encrypt证书。以下是使用Certbot获取Let’s Encrypt证书的示例:
sudo apt-get updatesudo apt-get install certbot python3-certbot-nginxsudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

按照提示操作,Certbot会自动配置Nginx并生成SSL证书。

    配置Node.js应用程序在你的Node.js应用程序中,你需要使用https模块来创建一个HTTPS服务器。首先,确保你已经安装了所有必要的依赖项,然后按照以下示例修改你的应用程序代码:
const https = require('https');const fs = require('fs');const express = require('express'); // 或者其他你使用的Web框架const app = express();// 读取SSL证书文件const privateKey = fs.readFileSync('path/to/your/private-key.pem', 'utf8');const certificate = fs.readFileSync('path/to/your/certificate.pem', 'utf8');const ca = fs.readFileSync('path/to/your/ca.pem', 'utf8');// 创建HTTPS服务选项const credentials = { key: privateKey, cert: certificate, ca: ca };const httpsServer = https.createServer(credentials, app);// 启动HTTPS服务器httpsServer.listen(443, () => {console.log('HTTPS Server running on port 443');});

path/to/your/private-key.pempath/to/your/certificate.pempath/to/your/ca.pem替换为你的实际证书文件路径。

    重定向HTTP到HTTPS(可选)为了确保所有流量都通过HTTPS传输,你可以配置Nginx将HTTP请求重定向到HTTPS。以下是一个简单的Nginx配置示例:
server {listen 80;server_name yourdomain.com www.yourdomain.com;location / {return 301 https://$host$request_uri;}}

yourdomain.comwww.yourdomain.com替换为你的实际域名。

    重启Node.js应用程序和Nginx最后,重启你的Node.js应用程序和Nginx以应用更改:
sudo systemctl restart your-nodejs-appsudo systemctl restart nginx

现在,你的Node.js应用程序应该已经成功配置了SSL证书,并可以通过HTTPS访问了。