Nginx报错(2: No such file or directory)及多环境Node.js+React应用反向代理配置求助
Nginx报错(2: No such file or directory)及多环境Node.js+React应用反向代理配置求助
老哥,我来帮你捋捋这个问题!你遇到的Nginx报「No such file or directory」的错误,大概率是路径配置踩坑了,结合你说的多环境(test/prod)Node+React应用场景,咱们一步步梳理解决方案:
先明确你的目录结构(整理后更清晰)
- 生产环境(prod)
- 静态文件根目录:
/home/usr/app_name/prod/client/ - 后端服务目录:
/home/usr/app_name/prod/server/(建议后端监听端口3001)
- 静态文件根目录:
- 测试环境(test)
- 静态文件根目录:
/home/usr/app_name/test/client/ - 后端服务目录:
/home/usr/app_name/test/server/(建议后端监听端口3002,和prod区分开)
- 静态文件根目录:
核心问题分析&正确Nginx配置
你之前的配置没写完,但关键点是要区分/(prod)和/test/(test)的路由,还要注意root和alias的用法(这是很多人踩坑的地方),下面给你一份完整的可参考配置:
server { listen 3000 ssl; listen [::]:3000 ssl; # 替换成你实际的SSL证书路径 ssl_certificate /etc/nginx/ssl/your-cert.pem; ssl_certificate_key /etc/nginx/ssl/your-key.pem; # 替换成你的域名或服务器IP server_name your-domain.com; # -------------------------- 生产环境配置 -------------------------- # 根路径匹配prod的静态文件 location / { # 绝对路径必须写对!这是解决「找不到文件」错误的核心 root /home/usr/app_name/prod/client; index index.html; # React单页应用必备:刷新页面避免404 try_files $uri $uri/ /index.html; # 静态资源缓存优化(可选) location ~* \.(js|css|png|jpg|gif)$ { expires 7d; add_header Cache-Control "public, max-age=604800"; } } # 生产环境API请求转发到后端Node服务 location /api/ { proxy_pass http://localhost:3001/; # 传递请求头,保证后端能正确获取客户端信息 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; } # -------------------------- 测试环境配置 -------------------------- # /test/路径匹配test的静态文件 location /test/ { # 这里必须用alias!不能用root! # 因为访问/test/xxx会直接对应到alias目录下的xxx,而不是root/test/xxx alias /home/usr/app_name/test/client/; index index.html; # React单页应用刷新处理,注意这里是/test/index.html try_files $uri $uri/ /test/index.html; # 测试环境静态资源缓存 location ~* \.(js|css|png|jpg|gif)$ { expires 7d; add_header Cache-Control "public, max-age=604800"; } } # 测试环境API请求转发到后端Node服务 location /test/api/ { proxy_pass http://localhost:3002/api/; 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; } }
关键注意事项(必看!)
路径权限&正确性
- 确保Nginx有访问应用目录的权限:执行
sudo chmod -R 755 /home/usr/app_name/给目录加可读权限,或者把Nginx运行用户(默认是www-data)加入到你的用户组。 - 绝对路径一定要写对,别少写或多写目录层级,这是「No such file or directory」的最常见原因。
- 确保Nginx有访问应用目录的权限:执行
root vs alias的区别
- 当location是
/时用root:访问/index.html会对应root目录下的index.html - 当location是
/test/这种子路径时必须用alias:访问/test/index.html会对应alias目录下的index.html,如果用root会去找root/test/index.html,自然找不到文件!
- 当location是
后端端口区分
- test和prod的Node服务必须监听不同端口(比如3001和3002),否则两个服务会冲突启动失败。
配置验证&重启
- 配置写完后先检查语法错误:
sudo nginx -t,如果报错会明确提示哪里有问题。 - 验证通过后重启Nginx:
sudo systemctl restart nginx
- 配置写完后先检查语法错误:
Node服务状态检查
- 确认两个环境的Node服务都正常启动:
netstat -tulpn | grep node,能看到3001和3002端口被Node进程占用就没问题。
- 确认两个环境的Node服务都正常启动:
备注:内容来源于stack exchange,提问作者JhonesJGL
相关产品推荐
相关产品推荐

