应修改 Apache 的 DirectoryIndex 指令而非 index.php 文件本身,因其仅按该指令列出的文件名顺序查找首页;需编辑 httpd.conf 中的 DirectoryIndex 行(如改为 DirectoryIndex home.php index.php index.html),并重启 Apache 生效。

直接改 DirectoryIndex 行,重启 Apache,别碰 index.php 文件本身——它不是配置项,只是个普通文件。
为什么改了 index.php 还是不加载?
Apache 不会“认出”你改名的 index.php,它只按 DirectoryIndex 指令里写的顺序找文件。如果你把 index.php 改成 home.php,但 DirectoryIndex 里没写 home.php,Apache 就跳过它,继续往后找;如果后面也没匹配项,就返回 403(目录禁止列表)或 404(无默认页且禁用索引)。
-
DirectoryIndex默认值通常是index.html index.htm index.php,不含home.php - Apache 匹配是严格按顺序、逐个检查文件是否存在,找到第一个就停,不会合并或推断
- 即使目录里只有
home.php,只要它不在DirectoryIndex列表里,就不会被当作首页
怎么改 DirectoryIndex 才生效?
打开 XAMPP 的 httpd.conf(Windows: C:/xampp/apache/conf/httpd.conf;macOS/Linux: /opt/lampp/etc/httpd.conf),搜索 DirectoryIndex,找到类似这行:
DirectoryIndex index.html index.htm index.php
把它改成你想要的顺序,比如优先加载 home.php:
立即学习“PHP免费学习笔记(深入)”;
DirectoryIndex home.php index.php index.html index.htm
- 多个文件名必须用空格分隔,不能用逗号、换行或引号
- 顺序越靠前,优先级越高;
home.php在第一位,意味着只要它存在,就绝不加载后面的 - 改完必须重启 Apache(不是刷新页面),否则配置不加载
- 如果想让某子目录单独生效,可在该目录下放
.htaccess,内容一样:DirectoryIndex home.php index.php
常见踩坑点:权限、缓存和重定向干扰
改完 DirectoryIndex 却仍跳转或 403,大概率不是顺序问题,而是其他配置在“抢跑”:
-
htdocs/index.php文件还在,且含header('Location: /dashboard/');—— 它会先于DirectoryIndex触发重定向,删掉或重命名它(如index.php.bak) -
Options Indexes没开,而目标目录又没任何匹配的首页文件 → 返回 403;确认<Directory>块里有Options Indexes - 浏览器缓存了旧的 302 跳转,尤其从
localhost/访问时;用隐身窗口或清空缓存再试 - 某些 XAMPP 版本默认启用了
mod_dir以外的模块(如mod_rewrite),.htaccess 里的规则可能覆盖DirectoryIndex,临时注释掉相关RewriteRule
最常被忽略的是:改了 DirectoryIndex 后没重启 Apache,或者改错了文件(比如改了 httpd-vhosts.conf 里的虚拟主机配置,但主配置里仍有全局 DirectoryIndex 覆盖它)。



















