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

如何通过.htaccess让无index文件的现有目录加载指定template.php内容

解决方案

你原来的规则缺少「请求路径必须是真实存在的目录」的判断条件,所以会匹配到不存在的多级路径。你可以把下面的.htaccess配置放在/items/目录下即可满足需求:

DirectoryIndex index.html index.htm index.php
RewriteEngine On

# 限制只匹配服务器上真实存在的目录
RewriteCond %{REQUEST_FILENAME} -d
# 校验该目录下没有默认的索引文件
RewriteCond %{REQUEST_FILENAME}/index.html !-f
RewriteCond %{REQUEST_FILENAME}/index.htm !-f
RewriteCond %{REQUEST_FILENAME}/index.php !-f
# 重写到当前items目录下的template.php
RewriteRule ^ template.php [L]

规则说明

  • 核心的-d判断直接过滤了/items/aaa/bbb/zzz这类不存在的路径,完全不会触发重写
  • 三个索引文件存在性判断不会影响folder3这类自带index.php的目录正常访问
  • 规则仅在/items目录下生效,不会干扰根目录其他路由逻辑

如果你要把规则放在网站根目录的.htaccess里,可以使用下面的版本:

DirectoryIndex index.html index.htm index.php
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.html !-f
RewriteCond %{REQUEST_FILENAME}/index.htm !-f
RewriteCond %{REQUEST_FILENAME}/index.php !-f
RewriteRule ^items/(.+)$ /items/template.php [L]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:24:03