解决 Nginx 报错 Primary script unknown (FastCGI PHP 404) 的排查指南
排查与解决 Nginx 配合 PHP-FPM 处理动态请求页面输出 File not found 并在日志提示 Primary script unknown 的完整方案。
问题现象
访问由 Nginx 代理的 PHP 网页或 API 时,页面只返回简短纯文本:
File not found.
HTTP 状态码为 404。查看 Nginx 错误日志发现对应条目:
2026/11/15 17:00:20 [error] 9876#9876: *12 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 10.0.0.2, server: test.local, request: "GET /index.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php8.2-fpm.sock:", host: "test.local"
触发根因
SCRIPT_FILENAME参数拼接路径错误:PHP-FPM 是一个独立的外部进程,它必须在服务器文件系统上直接读取物理 PHP 文件。如果传递给 FastCGI 的脚本绝对路径不存在,PHP-FPM 便抛出Primary script unknown。root指令写在了location /内部,而不是定义在server块级,导致匹配到location ~ \.php$时丢失了root上下文,解析为空路径。- PHP 文件物理权限不足,PHP-FPM 运行用户(
www-data)无法读取该文件。
解决步骤与操作命令
步骤一:规范配置 SCRIPT_FILENAME 与全局 root 目录
在虚拟主机配置中,将 root 指令提升到 server 块的顶部,并在 FastCGI 中引用 $document_root:
server {
listen 80;
server_name test.local;
# 将 root 声明在 server 顶层,供所有 location 统一继承
root /var/www/html/public;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
# 确保精确传递绝对物理路径
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
步骤二:核实物理文件是否存在且权限正确
检查该路径下是否存在 index.php:
ls -la /var/www/html/public/index.php
确保所属用户与权限允许读取:
sudo chown -R www-data:www-data /var/www/html/public
sudo chmod -R 755 /var/www/html/public
步骤三:测试语法并重载
sudo nginx -t
sudo systemctl reload nginx
验证确认
再次请求 PHP 页面:
curl -I http://test.local/index.php
返回 HTTP 200 OK,PHP 脚本正常执行输出 HTML/JSON 内容,不再出现 File not found。


