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

Apache 2.4仅允许访问index.php,根目录localhost/无法访问问题

解决Apache .htaccess仅允许访问index.php且根路径可访问的问题

你的问题出在配置顺序和访问控制的匹配逻辑上:当访问localhost/时,请求路径是/,而<Files "index.php">只匹配文件名是index.php的请求,所以/的请求会被Require all denied直接拦截,Rewrite规则还没来得及生效就被拒绝了。

调整后的配置方案如下:

方案一:通过文件匹配规则兼容根路径

DirectoryIndex index.php

# 启用重写引擎
RewriteEngine On

# 根路径内部重定向到index.php(地址栏不会变化)
RewriteRule ^$ index.php [L]

# 默认拒绝所有请求
Require all denied

# 允许index.php和根路径的请求
<FilesMatch "^(index\.php|)$">
    Require all granted
</FilesMatch>

方案二:用Rewrite规则统一控制访问(更简洁)

DirectoryIndex index.php

RewriteEngine On

# 拦截所有非根路径、非index.php的请求,返回403
RewriteCond %{REQUEST_URI} !^/(index\.php)?$
RewriteRule ^ - [F,L]

# 根路径内部重定向到index.php
RewriteRule ^$ index.php [L]

关键说明

  • 方案一中的<FilesMatch>用正则同时匹配index.php和空字符串(对应根路径请求),确保两种请求都能通过访问控制,其余请求全部拒绝。
  • 方案二直接通过Rewrite规则拦截非法请求,逻辑更直观,不需要额外的Require配置。
  • 确保Apache已启用mod_rewrite模块,且网站目录的AllowOverride设置为All(在httpd.conf或虚拟主机配置中),否则.htaccess配置不会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 03:21:02