PHP应用返回404通常因Web服务器未正确配置默认索引文件:Apache需在DirectoryIndex中显式添加index.php并重启服务;Nginx需在server块中配置index index.php index.html且确保生效;PHP-FPM还需校验SCRIPT_FILENAME路径是否正确。

PHP 应用返回 404,往往不是 PHP 本身出错,而是 Web 服务器(如 Apache 或 Nginx)没找到要执行的默认文件,根本没把请求交给 PHP 处理。
Apache 的 DirectoryIndex 没配对
Apache 默认只认 index.html 或 index.htm,不自动包含 index.php。如果项目入口是 index.php,但配置里没写上,访问根路径就会 404。
- 检查
.htaccess文件是否含DirectoryIndex index.php index.html(顺序影响优先级) - 若用虚拟主机配置,确认
块中有DirectoryIndex index.php index.html - 修改后必须重启 Apache:
sudo systemctl restart apache2(Ubuntu/Debian)或sudo apachectl graceful
Nginx 的 index 指令漏了 index.php
Nginx 不像 Apache 那样默认支持 PHP 索引,index 指令必须显式列出 index.php,否则即使 location ~ \.php$ 转发正常,根路径请求也进不了 PHP。
- 在
server块中确认有:index index.php index.html; - 确保
location /或location ~ ^/$能匹配根路径,并继承index指令 - 常见错误:只在
location ~ \.php$里写index,这无效——index必须在server或location /级别声明
PHP-FPM 或 FastCGI 没正确处理 index.php 路径
即使 Web 服务器找到了 index.php,若 SCRIPT_FILENAME 传给 PHP-FPM 的路径错误(比如少了一级目录、用了相对路径),PHP 会报 404 或 “No input file specified”。
立即学习“PHP免费学习笔记(深入)”;
- Apache + mod_php 一般无此问题;但用
ProxyPassMatch或SetHandler "proxy:fcgi://..."时,需检查ProxySet或SetEnvIf是否干扰了SCRIPT_FILENAME - Nginx 中重点核对:
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;——$document_root必须真实指向含index.php的目录 - 可在
index.php开头加var_dump($_SERVER['SCRIPT_FILENAME']); die();
看实际传入路径是否可读
最常被忽略的是:改完配置后没重载服务,或改了子配置却忘了 include 到主配置里。Nginx 尤其容易因 include 路径错误导致新 index 指令完全没生效。











