配置Nginx HTTPS(443端口)反向代理遇阻求助
Nginx反向代理Node.js应用无法通过HTTPS无缝访问问题排查与解决
目标
无需在URL中指定端口,通过HTTPS(443端口)访问Node.js应用
已尝试操作
- 网络配置:路由器设置端口转发规则
Public 80 -> Private 80 Public 443 -> Private 443 Public 8080 -> Private 8080 - Node.js Express服务器配置:应用监听8080端口,
server/index.js代码如下const express = require('express'); const routes = require('./routes'); const path = require('path'); const app = express(); const httpPort = 8080; app.use(express.json()); app.use('/api', routes); app.use(express.static(path.join(__dirname, "../client", "dist"))); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, "../client", "dist", "index.html")); }); app.listen(httpPort, () => { console.log(`Server running on http://localhost:${httpPort}`); }); - Nginx配置:实现HTTP转HTTPS重定向,将443端口流量代理至Node.js的8080端口
server { listen 80; server_name MY_SERVER_NAME; # Redirect HTTP to HTTPS return 301 https://$host$request_uri; } server { listen 443 ssl; server_name MY_SERVER_NAME; ssl_certificate /home/<user>/certificates/fullchain.pem; ssl_certificate_key /home/<user>/certificates/privkey.pem; location / { proxy_pass http://localhost:8080; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } - 防火墙规则(UFW):开放必要端口
To Action From 443/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere 8080/tcp ALLOW Anywhere - 套接字检查:执行
ss -tuln查看活跃套接字,结果如下tcp LISTEN 0 511 0.0.0.0:443 0.0.0.0:* tcp LISTEN 0 511 *:8080 *:*
问题现象
完成上述配置后,仍无法通过https://MY_SERVER_NAME无缝访问应用,必须手动指定端口,具体情况:
https://MY_SERVER_NAME:443:无法访问,页面加载后提示ERR_CONNECTION_CLOSEDhttps://MY_SERVER_NAME:80:无法访问,自动重定向至https://MY_SERVER_NAME:443http://MY_SERVER_NAME:8080:可正常访问- ping或curl服务器均无数据包返回
更新尝试
后续做了以下调整:
- 删除
/etc/nginx/sites-available中的默认文件 - 修改Node.js应用监听端口
- 调整路由器端口映射:
Public 80 -> Private {new node port} Public 445 -> Private {new node port}
修改后访问情况:
https://MY_SERVER_NAME:443:无法访问https://MY_SERVER_NAME:80:无法访问,重定向至https://MY_SERVER_NAME:443http://MY_SERVER_NAME:{new Node Port}:无法访问https://{MyPublicIP}:无法访问https://{MyPublicIP}:{new Node Port}:可正常访问localhost:可正常访问https://{IPV4}:可正常访问
疑问:私有网络端口应指向Node.js端口,还是公网与私网端口需保持一致?
问题解决
问题根源是网络环回限制:网络不允许外部连接环回至自身,导致本地网络无法通过域名访问,但应用本身在外部网络可正常访问。
解决步骤
修改Windows系统hosts文件:C:\Windows\System32\drivers\etc\host,添加以下内容:
192.168.x.x {your DNS}
其中192.168.x.x是运行应用的服务器内网IPv4地址(示例:192.168.0.10),{your DNS}是你的域名(示例:mywebsite.local)。
同类问题判断方法
使用其他网络(如手机移动数据)访问网站,若能正常访问但本地网络无法访问,大概率是遇到了网络环回问题。
内容的提问来源于stack exchange,提问作者Only_a_codder
相关产品推荐
相关产品推荐

