如何配置Nginx反向代理NodeJS应用?/api路径404问题排查
排查Nginx反向代理NodeJS应用的404问题
你的问题出在Nginx转发请求时的路径处理上:
当访问my_domain/api时,Nginx会将完整的请求路径/api转发给本地3000端口的Node应用,但你的Node代码中并没有定义/api这个路由,因此返回cannot GET /api的404错误。
解决方案
有两种可行的修复方式,根据你的需求选择:
方式一:修改Nginx配置,移除/api前缀转发
修改location /api块中的proxy_pass指令,添加末尾的斜杠/,这样Nginx会把/api之后的路径映射到Node应用的根路径:
location /api { proxy_pass http://localhost:3000/; # 注意末尾的斜杠 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; }
修改后:
- 访问
my_domain/api→ Node收到GET / - 访问
my_domain/api/products→ Node收到GET /products
方式二:修改NodeJS代码,添加/api前缀路由
在Node应用中给所有路由统一添加/api前缀,确保能匹配Nginx转发的请求:
const express = require('express'); const app = express(); const router = express.Router(); app.use(express.json()); // 用router定义所有业务路由 router.get('/', (req, res) => { res.send('<div><h1>Hello world</h1></div>') }) router.get('/products', (req, res) => { res.send('<div><h1>All Products</h1></div>') }) router.get('/products/:id', (req, res) => { const id = req.params.id res.send(`<div><h1>Product: ${id}</h1></div>`) }) // 给router添加/api前缀 app.use('/api', router); const PORT = 3000; app.listen(PORT, () => { console.log(`App listening on port ${PORT}`) })
验证步骤
- 保存修改后的配置/代码
- 重启Nginx:
sudo systemctl restart nginx - 重启Node应用
- 测试访问
my_domain/api和my_domain/api/products,确认返回正常内容
内容的提问来源于stack exchange,提问作者jim
相关产品推荐
相关产品推荐

