是Nginx转发问题而非PHP-FPM挂了;需检查fastcgi_pass配置、SCRIPT_FILENAME路径及location匹配顺序,确认PHP文件在root目录下且权限正确。

PHP Nginx配错致404怎么办_PHP Nginx404错误调整法【指导】  第1张

确认是 Nginx 转发问题,不是 PHP-FPM 挂了

看到 404 Not Found 页面时,先别急着改 nginx.conf。很多情况其实是 PHP-FPM 根本没响应,Nginx 默认返回 404(尤其在 try_files 配置错误时)。用 curl -I http://localhost/info.php 看响应头:HTTP/1.1 404 Not Found 是 Nginx 层拦截;如果是 502 Bad Gateway,说明 PHP-FPM 没通——那得查 php-fpm.sock 路径、权限或服务状态。

检查 location 块里有没有漏掉 fastcgi_pass

最常见错误:写了 location ~ \.php$,但里面只配了 rootindex,忘了传给 PHP 处理。Nginx 不会自动把 .php 文件丢给 PHP-FPM,必须显式声明。

  • fastcgi_pass 必须指向有效的 PHP-FPM 地址,比如 unix:/var/run/php/php8.1-fpm.sock127.0.0.1:9000
  • 路径要和 php-fpm.conflisten = 的值严格一致(注意权限:sock 文件需 Nginx worker 进程用户可读写)
  • 别漏掉 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;,否则 PHP 收不到真实文件路径,常报“File not found”

try_files 写错直接屏蔽所有 PHP 请求

很多人照抄 WordPress 或 Laravel 的配置,在 location / 里写 try_files $uri $uri/ /index.php?$query_string;,却没同步改 location ~ \.php$ 块——结果所有 .php 请求先被 try_files 匹配到 $uri,发现文件不存在就跳去 /index.php,而 /index.php 又不匹配 location ~ \.php$,最终 404。

正确做法是把 PHP 处理逻辑单独拎出来,且确保优先级高于通用 try_files

location / {
    try_files $uri $uri/ /index.html;
}

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

PHP 文件实际路径和 Nginx root 不一致

Nginx 的 root 定义的是 URL 到文件系统的映射根目录。比如 root /var/www/myapp;,那么访问 http://site.com/index.php 对应的文件是 /var/www/myapp/index.php。如果 PHP 文件放在 /var/www/html/index.php,但 root 写成 /var/www/myapp,Nginx 就找不到它——连传给 PHP-FPM 的机会都没有。

  • ls -l /var/www/your-root-dir/ 确认 PHP 文件确实在那里
  • 检查 root 路径末尾有没有多余斜杠(/var/www/app//var/www/app 在某些场景下行为不同)
  • 如果用了 alias,注意它不拼接 $urialias /path/ + location /api/ → 实际路径是 /path/,不是 /path/api/
Nginx 的 404 往往不是“找不到 PHP”,而是“根本没让 PHP 知道有这个请求”。重点盯住 location 匹配顺序、fastcgi_pass 是否生效、SCRIPT_FILENAME 是否指向真实路径这三点,比反复 reload 更有效。