Nginx反向代理部署网站与Node.js应用:重定向及静态文件问题
网站部署问题:重定向错误与Express静态目录服务异常
一、初始重定向错误情况
- 网站部署在
https://mydomain.co.uk,表单依赖nodemailer,通过server.js与app.js处理表单数据 - 配置Nginx作为反向代理,
mydomain.co.uk的server块配置如下:
location / { proxy_pass http://localhost:80; 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; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. # try_files $uri $uri/ =404; }
- 访问时出现too many redirects错误,此前已通过certbot配置HTTPS,未配置反向代理时运行正常
- 使用pm2运行
server.js,启动命令:pm2 start ecosystem.config.js --env production,ecosystem.config.js配置:
module.exports = { apps : [ { name: "myserver", script: "server.js", watch: true, env: { "PORT": 3000, "NODE_ENV": "development" }, env_production: { "PORT": 80, "NODE_ENV": "production", } } ] }
二、调整后静态目录服务异常情况
后续调整了Nginx配置与server.js代码:
修改后的Nginx配置
location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. # try_files $uri $uri/ =404; 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_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_cache_bypass $http_upgrade; add_header X-Cache-Status $upstream_cache_status; }
修改后的server.js代码片段
var path = require("path"); const express = require("express"); const app = express(); const nodemailer = require("nodemailer"); const PORT = process.env.PORT || 5500; // CHANGE TO WHATEVER // middleware var htmlPath = path.join(__dirname, "/html"); // app.use(express.static("public")); app.use(express.static(htmlPath)); app.use(express.json());
当前反向代理功能正常,但Express仅能返回单个HTML文件,无法服务整个html目录,需解决如何配置让Express服务整个目录的问题。
内容的提问来源于stack exchange,提问作者Yenmangu
相关产品推荐
相关产品推荐

