【发布时间】:2019-07-07 20:03:25
【问题描述】:
我使用 Nginx 作为反向代理,使用 Node.js Express 服务器作为后端。
当尝试在 Express 上加载定制的 404 页面时,Nginx 总是返回 200 状态码,即使 Express 正确地向 Nginx 发送回 404 状态码。
配置有什么问题?
我也使用 EJS 作为模板引擎,但是,我认为它不会导致问题。我使用 PM2 作为进程管理器来运行服务器。我在没有使用 Nginx 作为反向代理的情况下进行了测试,Express 中的一切似乎都运行良好,即 Express 正确返回了 404 状态码。
这是我的快递代码:
const path = require('path')
const express = require('express')
const app = express()
const port = process.argv[2] || 3000
// Define paths for Express config
const publicDirPath = path.join(__dirname, '../public')
const viewsPath = path.join(__dirname, '../templates/views')
// Set EJS engine and views location
app.set('view engine', 'ejs')
app.set('views', viewsPath)
// Set static files location
app.use(express.static(publicDirPath))
app.get('/testing404', (req, res) => {
res.status(404).render('404', {
title: '404 error',
content: 'This is a 404 error page.'
})
})
app.listen(port, () => {
console.log('Server started at port ' + port + '!')
})
这是我的相关 Nginx 配置:
upstream nthreads {
ip_hash;
server localhost:3000;
}
server {
root /var/www/[XXXXX]/html;
index index.html index.htm index.nginx-debian.html;
server_name [XXXXX] www.[XXXXX];
location / {
proxy_pass http://nthreads;
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;
}
}
如前所述,我希望 Nginx 通过 Node.js Express 后端服务器返回 404 状态码,但我得到的是 200 状态码,那么问题出在哪里?
【问题讨论】: