部署Angular+Laravel至Ubuntu Nginx后API报404故障求助
问题排查与修复方案
核心问题定位
本地Laravel内置服务器(localhost:8000)能正常响应API,但Nginx部署后API返回404,说明问题集中在Nginx路由转发逻辑、Laravel环境配置或文件权限这几个环节。
具体解决步骤
1. 修正Nginx的API转发配置
你的Nginx配置可能未正确将/api请求导向Laravel的入口文件。参考以下配置调整:
server { listen 80; server_name your-domain-or-ip; # 替换为你的域名/虚拟机IP # Angular前端根目录 root /path/to/angular/dist; index index.html; # 处理SPA路由(刷新页面不404) location / { try_files $uri $uri/ /index.html; } # API请求转发到Laravel后端 location /api { root /path/to/laravel/public; # 必须指向Laravel的public目录 try_files $uri $uri/ /index.php$is_args$args; # PHP-FPM配置,适配你的PHP版本 fastcgi_pass unix:/run/php/php8.2-fpm.sock; # 用find /run/php/ 确认实际sock路径 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
关键注意点:
/api块的root必须指向Laravel的public目录,而非项目根目录try_files规则要确保所有API请求都经过index.php处理- 确认PHP-FPM的sock路径正确,不同PHP版本路径会有差异
2. 调整Laravel环境配置
- 编辑Laravel根目录的
.env文件:- 设置
APP_URL为线上域名/IP(如http://your-domain-or-ip) - 将
APP_ENV设为production,避免调试模式干扰路径解析
- 设置
- 清理Laravel缓存(在项目根目录执行):
php artisan cache:clear php artisan route:clear php artisan config:clear
3. 修复文件权限问题
Nginx运行用户通常是www-data,需确保Laravel关键目录有读写权限:
sudo chown -R www-data:www-data /path/to/laravel sudo chmod -R 755 /path/to/laravel/storage sudo chmod -R 755 /path/to/laravel/bootstrap/cache
4. 验证配置并重启服务
- 检查Nginx配置合法性:
sudo nginx -t - 无报错则重启Nginx:
sudo systemctl restart nginx
5. 日志排查
若问题仍存在,查看Nginx错误日志定位具体原因:
tail -f /var/log/nginx/error.log
日志会显示404是因为文件不存在还是路由转发失败,进一步缩小排查范围。
内容的提问来源于stack exchange,提问作者Frevelman
相关产品推荐
相关产品推荐

