Nginx生产环境下Angular+Laravel应用API请求异常排查
问题分析与解决方案
你的Nginx配置存在核心逻辑冲突,导致/api请求处理混乱,具体问题和修复方案如下:
1. 配置冲突根源
你在location /api块中同时混用了两种互斥的请求处理逻辑:
proxy_pass http://localhost:8001:将请求反向代理到Laravel内置服务器try_files+fastcgi_pass:直接通过PHP-FPM解析Laravel本地文件
两种逻辑叠加导致Nginx无法正确识别/api请求的处理规则,最终返回Angular的HTML页面而非Laravel的JSON响应。
2. 修复方案(二选一)
方案一:PHP-FPM直接处理Laravel(生产环境推荐)
删除反向代理相关配置,让Nginx直接通过PHP-FPM解析Laravel文件,调整后的配置如下:
server { include mime.types; listen 80; listen [::]:80; server_name 207.154.202.138; # 处理Angular前端请求 location / { root /var/www/html/myForum/forum-frontend/public; try_files $uri $uri/ /index.html; } # 处理Laravel API请求 location /api { root /var/www/html/myForum/forum-api/public; index index.php; # 注意:最后要指向/api/index.php,匹配location前缀与Laravel入口路径 try_files $uri $uri/ /api/index.php?$query_string; location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.2-fpm.sock; # 强制指定脚本路径,避免解析错误 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } } }
方案二:反向代理到Laravel内置服务器(开发/测试场景)
如果你确实需要通过php artisan serve运行Laravel,需删除PHP-FPM相关配置,保证反向代理逻辑纯净:
server { include mime.types; listen 80; listen [::]:80; root /var/www/html/myForum/forum-frontend/public; index index.html; server_name 207.154.202.138; location / { try_files $uri $uri/ /index.html; } location /api { proxy_pass http://localhost:8001; 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; } }
注意:需确保Laravel内置服务器在8001端口正常运行,执行命令:
php artisan serve --port=8001 --host=0.0.0.0
3. 验证与补充操作
- 重启Nginx生效配置:
sudo systemctl restart nginx - 修复Laravel目录权限:
sudo chown -R www-data:www-data /var/www/html/myForum/forum-api/storage /var/www/html/myForum/forum-api/bootstrap/cache sudo chmod -R 775 /var/www/html/myForum/forum-api/storage /var/www/html/myForum/forum-api/bootstrap/cache - 测试/api路径:直接访问
http://207.154.202.138/api/,确认是否返回Laravel JSON响应。
可能需要补充的排查信息
- Laravel的实际运行方式(PHP-FPM/内置服务器)
- Nginx错误日志内容:
sudo tail -f /var/log/nginx/error.log - Laravel应用日志内容:
/var/www/html/myForum/forum-api/storage/logs/laravel.log
内容的提问来源于stack exchange,提问作者Armando_pagano
相关产品推荐
相关产品推荐

