You need to enable JavaScript to run this app. nginx多location配置下原生PHP项目路由返回403 Forbidden错误
优惠活动
大模型
产品
解决方案
定价
更多

nginx多location配置下原生PHP项目路由返回403 Forbidden错误

403报错的核心触发原因

访问/admin路径返回403,是三处配置错位叠加导致的:

  • Nginx的location匹配规则中,正则类型的location(如配置里的location ~ \.php$)优先级远高于普通前缀location(如配置里的location /admin),所有以.php结尾的/admin路径请求,根本不会走到/admin配置块,会直接被全局正则块拦截。
  • 全局正则PHP块继承了server级别的根目录/var/www/html/washyapi/public,处理/admin下的PHP请求时,会把脚本路径拼成/var/www/html/washyapi/public/admin/xxx.php,这个路径在磁盘上根本不存在,Nginx找不到对应执行脚本,又未开启目录列文件权限,就会直接返回403。
  • location /admin块没有配置对应的请求校验规则,访问/admin根路径时,Nginx无法正确定位到目录下的index.php入口文件,同样会因为没有权限列目录内容触发403。

具体修复方案

  • 参照配置里phpmyadmin的处理逻辑,把/admin路径下的PHP处理规则内嵌到location /admin块内部,让/admin范围内的PHP请求优先走自身块内的规则,不被全局的正则PHP块拦截。
  • 校验原生PHP项目的存放路径:如果admin项目实际放在/var/www/html/admin目录下,/admin块里写的root /var/www/html/配置是正确的,需要确保该目录的权限开放给www-data用户读取、执行,避免因为文件权限不足触发403。
  • 清理冗余配置:location /块里连续写了两行重复的try_files规则,删掉无效的那行,保留Laravel标准的路由规则try_files $uri $uri/ /index.php?$query_string;即可,避免逻辑冲突。

修复后可直接套用的配置片段

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    # 保持Laravel项目的全局根目录配置不变
    root /var/www/html/washyapi/public;
    index index.html index.htm index.php;
    server_name 167.71.239.178;

    location / {
        # 清理冗余的try_files,保留Laravel标准路由规则
        try_files $uri $uri/ /index.php?$query_string;
    }

    location /admin {
        # 对应admin项目实际存放的根路径
        root /var/www/html/;
        index index.php;

        # 内嵌admin路径下的PHP处理规则,避免被全局正则块拦截
        location ~ ^/admin/(.+\.php)$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include /etc/nginx/fastcgi_params;
        }
    }

    # 全局PHP处理块保持原配置,供Laravel项目使用
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }

    # 原有phpmyadmin配置保持不变
    location /phpmyadmin {
        root /usr/share/;
        index index.php index.html index.htm;
        location ~ ^/phpmyadmin/(.+\.php)$ {
            try_files $uri =404;
            root /usr/share/;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include /etc/nginx/fastcgi_params;
        }
        location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ {
            root /usr/share/;
        }
    }
}

后续验证步骤

  • 配置修改完成后,先执行nginx -t检查配置语法正确性,确认无报错后执行systemctl reload nginx重载服务。
  • 如果仍然报403,直接查看/var/log/nginx/error.log里对应的报错记录,常见遗留问题包括admin目录权限未分配给www-data、root路径配置和实际项目存放路径不匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.29 00:06:05