You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NGINX中带api前缀的Laravel API与Angular前端配置故障排查

排查Laravel API在Nginx下无法运行的问题

我来帮你一步步梳理可能的问题,从配置到项目本身逐一排查:

1. Nginx配置中location /api的路径逻辑问题

你当前用alias指向api/public,但try_files里的/index.php?$args会直接指向服务器根目录(也就是前端项目所在的目录)下的index.php,而不是Laravel的入口文件,这是核心问题之一。

你可以把location /api的配置改成下面这样,修复路径解析的问题:

location /api {
    alias /var/www/my_domain.com/api/public;
    try_files $uri $uri/ @api_rewrite;

    # 嵌套PHP解析规则,避免alias带来的路径混淆
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        # 手动指定脚本路径,确保指向Laravel的入口文件
        fastcgi_param SCRIPT_FILENAME $request_filename;
    }
}

# 处理Laravel的路由重写
location @api_rewrite {
    rewrite ^/api/(.*)$ /api/index.php?$1 last;
}

或者换用更直观的root方式配置:

location /api {
    root /var/www/my_domain.com/api/public;
    try_files $uri $uri/ /api/index.php?$query_string;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

2. Laravel项目本身的配置与权限检查

即使Nginx配置正确,Laravel自身的问题也会导致API罢工:

  • 文件权限修复:Laravel需要storage和bootstrap/cache目录有写入权限,执行以下命令:
    sudo chown -R www-data:www-data /var/www/my_domain.com/api/storage /var/www/my_domain.com/api/bootstrap/cache
    sudo chmod -R 775 /var/www/my_domain.com/api/storage /var/www/my_domain.com/api/bootstrap/cache
    
  • 环境配置验证:打开api/.env文件,确保APP_URL=http://my_domain.com/api,数据库连接参数正确,同时生成应用密钥:
    cd /var/www/my_domain.com/api
    php artisan key:generate
    
  • 依赖安装:如果是新部署的项目,别忘了安装Composer依赖:
    cd /var/www/my_domain.com/api
    composer install --no-dev
    

3. 查看错误日志定位具体问题

如果上面的调整后还是不行,直接看日志能快速找到病根:

  • 查看Nginx错误日志:tail -f /var/log/nginx/error.log
  • 查看PHP-FPM错误日志:tail -f /var/log/php7.4-fpm.log

日志里会明确告诉你是文件找不到、权限不够,还是Laravel代码抛出了异常,跟着提示修复就好。

内容的提问来源于stack exchange,提问作者camille

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:47:32