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

NGINX新手配置PHP路由遭遇404错误求助

问题分析与解决方案

你的问题核心是NGINX配置中/apollo/区块的请求转发路径错误:当访问子页面(如/apollo/home)时,NGINX找不到对应文件后,会转发到根目录的index.php,而非/apollo/public/下的目标入口文件,导致根目录的PHP脚本无法处理该路径,返回404。

修改步骤

1. 修正/apollo/区块的配置

调整try_files指令的转发目标,并明确索引文件,确保请求能正确落到/apollo/public/index.php:

location /apollo/ {
    auth_basic "Use Your Developer Login To Enter!";
    auth_basic_user_file /etc/nginx/conf.d/.htpasswd;
    alias /var/www/example.com/apollo/public/;
    index index.php; # 添加索引文件指定,确保目录访问时加载入口
    try_files $uri $uri/ /apollo/index.php$is_args$args; # 修改转发目标为apollo的入口文件

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $request_filename;
    }
}

2. 验证配置并重启NGINX

先检查配置语法是否合法:

nginx -t

如果输出test is successful,重启NGINX使配置生效:

systemctl restart nginx

原理说明

  • index index.php:确保直接访问/apollo/目录时,自动加载public/index.php
  • 修改后的try_files:当请求的文件/目录不存在时,转发到/apollo/index.php,同时保留原请求参数($is_args$args用于处理带参数的请求,如/apollo/summoner?name=test)
  • 该配置保证所有/apollo/下的请求最终都由你的apollo/public/index.php处理,匹配你写的PHP路由逻辑

额外检查项

  • 确认/var/www/example.com/apollo/public/index.php文件存在,且NGINX运行用户(通常是www-data)有读取权限
  • 检查PHP-FPM服务状态:systemctl status php8.1-fpm,确保服务正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 16:33:10