温馨提示×

Ubuntu上Node.js如何配置HTTPS

小樊
42
2025-12-08 18:17:48
栏目: 编程语言

在Ubuntu上配置Node.js应用程序以使用HTTPS涉及几个步骤。以下是一个基本的指南,帮助你设置HTTPS服务器:

1. 安装Node.js和npm

如果你还没有安装Node.js和npm,可以使用以下命令进行安装:

sudo apt update
sudo apt install nodejs npm

2. 创建Node.js应用程序

创建一个新的Node.js应用程序或打开现有的应用程序。假设你已经有一个简单的HTTP服务器:

// server.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(3000, '127.0.0.1', () => {
  console.log('Server running at http://127.0.0.1:3000/');
});

3. 获取SSL证书

你可以使用Let’s Encrypt免费获取SSL证书。首先,安装Certbot:

sudo apt install certbot python3-certbot-nginx

然后,运行Certbot来获取证书:

sudo certbot --nginx -d yourdomain.com

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

4. 配置Nginx作为反向代理

Certbot会自动配置Nginx来使用SSL证书,并将流量转发到你的Node.js应用程序。你需要编辑Nginx配置文件:

sudo nano /etc/nginx/sites-available/yourdomain.com

添加以下配置:

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;
        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;
    }
}

保存并退出编辑器,然后启用该站点:

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

5. 更新Node.js应用程序以使用HTTPS

修改你的Node.js应用程序以监听HTTPS端口,并使用SSL证书:

// server.js
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')
};

const server = https.createServer(options, (req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n');
});

server.listen(443, '0.0.0.0', () => {
    console.log('Server running at https://yourdomain.com/');
});

6. 重启Node.js应用程序

确保你的Node.js应用程序正在运行,并且监听HTTPS端口:

node server.js

7. 验证配置

打开浏览器并访问https://yourdomain.com,你应该能够看到你的Node.js应用程序通过HTTPS提供服务。

通过以上步骤,你已经在Ubuntu上成功配置了Node.js应用程序以使用HTTPS。

0