要在 Linux 上配置 Node.js 以支持 HTTPS,您需要完成以下步骤:
获取 SSL 证书:首先,您需要获得一个 SSL 证书。您可以从证书颁发机构(CA)购买证书,或者使用 Let’s Encrypt 提供的免费证书。对于开发和测试目的,您还可以创建一个自签名证书。
安装 Node.js:如果您尚未安装 Node.js,请访问官方网站(https://nodejs.org/)下载并安装适用于 Linux 的 Node.js 版本。
创建一个简单的 HTTP 服务器:在开始配置 HTTPS 之前,您需要创建一个简单的 HTTP 服务器。创建一个名为 server.js
的文件,并添加以下代码:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!\n');
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
server.js
文件中,导入 https
模块并使用您的 SSL 证书创建一个 HTTPS 服务器。将以下代码添加到 server.js
文件中:const fs = require('fs');
const https = require('https');
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');
const credentials = { key: privateKey, cert: certificate, ca: ca };
const httpsServer = https.createServer(credentials, (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!\n');
});
const PORT = process.env.PORT || 3000;
httpsServer.listen(PORT, () => {
console.log(`HTTPS Server running at https://localhost:${PORT}/`);
});
请确保将 'path/to/your/private-key.pem'
、'path/to/your/certificate.pem'
和 'path/to/your/ca.pem'
替换为您的实际证书文件路径。
server.js
文件的目录,并运行以下命令启动 HTTPS 服务器:node server.js
现在,您的 Node.js 应用程序将在端口 3000 上通过 HTTPS 运行。您可以通过访问 https://localhost:3000
来测试它。由于我们使用的是自签名证书,浏览器可能会显示安全警告。在生产环境中,您应该使用由受信任的证书颁发机构颁发的证书。