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

Laravel/Nginx 403 Forbidden:子路径domain.com/path访问异常求助

Nginx子路径部署Laravel出现403错误的解决方法

问题场景

服务器上部署了两个Web应用:WordPress运行在顶级域名domain.com,Laravel需运行在子路径domain.com/path。当前Nginx配置如下:

server {
    listen 80;
    server_name domain.com www.domain.com;
    root /home/domain/root3;

    access_log /var/log/nginx/domain_access.log;
    error_log /var/log/nginx/domain_error.log;

    location / {
        root /home/domain/root3;
        index index.php index.html;
        try_files $uri $uri/ /index.php?$args;
    }
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    error_page 404 /index.php;

    location /path {
        alias /home/domain/laravel/public;
        try_files $uri $uri/ /index.php?$query_string;

        location ~ \.php$ {
            fastcgi_pass unix:/run/php/php8.1-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            include fastcgi_params;
        }
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass 127.0.0.1:9001;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param REQUEST_URI $request_uri;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        #fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

    location ~ /\.ht {
        deny all;
    }

    client_max_body_size 500M;

    location /upstream {
        proxy_ssl_server_name on;
        try_files $uri $uri/ /index.php?$query_string;
    }
}

访问domain.com/path时出现403错误,错误日志内容:

2023/05/17 17:30:49 [error] 26216#26216: *185 directory index of "/home/domain/laravel/public/" is forbidden, client: X.X.X.X, server: domain.com, request: "GET /path/ HTTP/1.1", host: "domain.com"

补充说明:直接访问domain.com/path/index.php时Laravel可正常运行,WordPress站点无异常,且已确认所有权限和所有权配置正确。

问题分析与解决方案

错误日志明确显示“目录索引被禁止”,核心原因有两个:

  1. location /path块未指定默认索引文件,导致访问目录时Nginx无法自动定位到index.php;
  2. try_files的最后参数错误,原配置中/index.php会指向WordPress的入口文件,而非Laravel的。

修改后的location /path配置

location /path {
    alias /home/domain/laravel/public;
    index index.php; # 添加默认索引指定
    try_files $uri $uri/ /path/index.php?$query_string; # 修正入口文件路径

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        include fastcgi_params;
    }
}

关键修改点解释

  • 添加index index.php;:明确告诉Nginx,当访问/path/目录时,默认使用index.php作为入口文件;
  • 调整try_files最后参数为/path/index.php?$query_string:确保当请求的文件或目录不存在时,路由到Laravel的入口文件,而非WordPress的。

修改完成后,重启Nginx服务即可解决403问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 17:17:39