Nginx访问任意页面均显示index.html故障排查求助
故障原因
- Node.js服务逻辑硬编码,无论接收什么路径的请求,都固定返回
myapp/index.html,没有实现请求路径和本地文件的匹配逻辑 - Nginx配置不合理,所有
/路径下的请求都被转发到了3000端口的Node.js服务,原本可以直接由Nginx返回的静态文件也走了Node服务的逻辑
解决方案
方案一:调整Nginx配置(推荐,性能更高)
静态资源(html、css、图片等)直接交给Nginx返回,仅动态请求走后端服务,修改Nginx配置如下:
server { listen 80 default_server; listen [::]:80 default_server; root /home/webstud/myapp ; index index.html index.htm; # 新增默认索引配置 server_name MYWEBSITE.COM; # 优先匹配本地静态文件,存在则直接返回,不存在再走Node服务 location / { try_files $uri $uri/ @node; } # Node服务转发规则 location @node { 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; } location /api { proxy_pass http://localhost:5000/backend; } }
修改完成后执行nginx -s reload重载配置即可生效。
方案二:修改Node.js代码适配静态文件请求
如果需要所有请求都走Node.js服务,可修改代码实现路径匹配逻辑:
const http = require('http') const fs = require('fs') const path = require('path') const server = http.createServer((req, res) => { // 根路径默认返回index.html let filePath = req.url === '/' ? '/index.html' : req.url const fullPath = path.join(__dirname, 'myapp', filePath) fs.readFile(fullPath, (err, data) => { if (err) { // 文件不存在返回404,单页应用可替换为返回index.html走前端路由 res.writeHead(404, { 'content-type': 'text/html' }) res.end('<h1>404 页面不存在</h1>') return } // 根据文件后缀设置对应Content-Type,可按需拓展更多类型 let contentType = 'text/html' if (fullPath.endsWith('.css')) contentType = 'text/css' if (fullPath.endsWith('.js')) contentType = 'application/javascript' if (fullPath.endsWith('.png')) contentType = 'image/png' if (fullPath.endsWith('.jpg')) contentType = 'image/jpeg' res.writeHead(200, { 'content-type': contentType }) res.end(data) }) }) server.listen(process.env.PORT || 3000)
修改完成后重启Node.js服务即可生效。
内容的提问来源于stack exchange,提问作者Mor
相关产品推荐
相关产品推荐

