You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

配置Let's Encrypt后Node.js HTTPS Express无法被浏览器访问

问题:Express HTTPS 服务无法加载(已配置 Nginx SSL 强制跳转)

背景:我已经按照教程为 Nginx 配置了 SSL,并且设置所有请求重定向到 HTTPS,访问 www.example.com 会正确跳转到 https://www.example.com 并显示 Nginx 默认页面。现在想运行 Express 服务,编写了以下测试脚本,但页面完全无法加载:

var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'), cert: fs.readFileSync('/etc/letsencrypt/live/example.com/cert.pem'), ca: fs.readFileSync('/etc/letsencrypt/live/example.com/chain.pem') }; https.createServer(options, function (req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8000);

核心问题:Nginx 未将请求转发到 Express 服务

你目前的 Nginx 还是指向默认的静态页面,没有把用户的请求传递给运行在 8000 端口的 Express 服务。另外还有几个细节需要调整,下面是分步解决办法:

1. 修改 Nginx 配置,添加反向代理

首先找到你的 Nginx 站点配置文件(通常在 /etc/nginx/sites-available/example.com 或者 /etc/nginx/conf.d/default.conf),打开后找到 HTTPS 的 server 块,替换掉默认的静态文件配置,改成反向代理规则:

server {
    listen 443 ssl;
    server_name example.com www.example.com;

    # 保留你的 SSL 证书配置
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # 把所有请求转发到本地的 Express 8000 端口
    location / {
        proxy_pass http://localhost:8000;
        # 传递必要的请求头,让 Express 能正确识别请求信息
        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;
    }
}

修改完成后,重启 Nginx 让配置生效:

sudo systemctl restart nginx

2. 简化 Express 配置:改用 HTTP 服务

既然已经用 Nginx 处理 SSL 终止(也就是用户和 Nginx 之间用 HTTPS,Nginx 和 Express 之间用本地 HTTP),完全不需要让 Express 再处理 HTTPS。这样既减少配置复杂度,也避免证书权限问题:

修改你的 Express 脚本为:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200);
    res.end("hello world\n");
}).listen(8000);

3. 检查关键细节

  • 证书权限:如果坚持要用 Express 的 HTTPS 服务,要注意 /etc/letsencrypt/live/ 目录的权限默认是 root 用户专属,普通用户运行 Express 会无法读取证书。要么用 root 用户启动(不推荐,有安全风险),要么调整证书文件的权限(也不推荐),所以更推荐用 Nginx 做反向代理的方案。
  • 端口监听状态:启动 Express 后,用下面的命令检查 8000 端口是否被正确监听:
    sudo lsof -i :8000
    
    如果没有输出,说明服务没启动,检查脚本是否有语法错误,或者证书路径是否正确。
  • 防火墙规则:确保本地回环(127.0.0.1)可以访问 8000 端口,通常默认是允许的,但如果有自定义防火墙规则,可以运行下面的命令开放:
    sudo ufw allow in from 127.0.0.1 to any port 8000
    

内容的提问来源于stack exchange,提问作者Michal Krůša

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:35:32