Windows11下Nginx特定路径请求转发至本地服务的问题
Nginx反向代理配置问题排查(Windows 11环境)
需求
- 指定一个真实网站作为目标站点
- 所有以
realwebsite.com/magic开头的请求,转发至本地localhost:3000服务 - 其他以
realwebsite.com开头的请求,直接路由到真实网站
已尝试操作
- 在
localhost:3000搭建Express服务器,确认直接访问可正常运行 - 修改
C:\Windows\System32\drivers\etc\hosts文件,添加映射:127.0.0.1 realwebsite.com - 修改Nginx配置文件
nginx.conf,新增以下服务器配置:
server { listen 80; server_name realwebsite.com; # 转发magic路径请求到本地服务 location /magic{ proxy_pass http://localhost:3000; 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; } # 其余请求转发至真实网站 location / { proxy_pass https://www.realwebsite.com; 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; } }
预期行为
访问realwebsite.com/magic时,浏览器应显示test.html文件内容
实际行为
访问realwebsite.com/magic时网站无法打开,本地localhost:3000服务器未记录任何GET请求;但直接访问localhost:3000时,服务器能正常记录请求日志
本地Express服务器代码
const express = require('express'); const path = require('path'); const app = express(); const PORT = 8080; const BASE_DIR = 'C:\\Users\\me\\Desktop\\Projects\\test\\server'; app.use('/magic', express.static(BASE_DIR)); app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); app.get('/magic/:filename', (req, res) => { const filePath = path.join(BASE_DIR, req.params.filename); res.download(filePath, (err) => { if (err) { console.error(err); res.status(404).send('File not found!'); } }); }); app.get('/magic', (req, res) => { const filePath = path.join(BASE_DIR, 'test.html'); res.sendFile(filePath, (err) => { if (err) { res.status(err.status).send('File not found!'); } }); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
内容的提问来源于stack exchange,提问作者derpascal
相关产品推荐
相关产品推荐

