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

求助:.htaccess实现子目录隐式指向index.php的配置问题

问题解决:子目录URL重写循环与无后缀访问修复

核心问题分析

你的配置存在两个关键问题:

  1. 无限循环:目录内部跳转规则与index.php重定向规则顺序错误,导致访问子目录时反复触发重写与跳转,形成/admin/index.php/index/index/...的循环。
  2. 子目录无后缀失效:原无后缀规则仅匹配根目录下的单级路径(^([^/.]+)$),无法覆盖/admin/meta这类子目录下的页面请求。

修正后的.htaccess配置

Options -Indexes

RewriteEngine On

# 1. 先处理暴露index.php的URL,重定向到干净路径(避免循环根源)
RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteRule ^(.*)/index\.php$ /$1 [R=301,L]

# 2. 语言切换规则(根目录)
RewriteRule ^en/?$ index.php?lang=en [L]
RewriteRule ^de/?$ index.php?lang=de [L]

# 3. 移除末尾斜杠(除根目录外)
RewriteCond %{REQUEST_URI} !^/$ 
RewriteCond %{REQUEST_URI} ^(.+)/$
RewriteRule ^ %1 [R=301,L]

# 4. 子目录内部加载index.php(不修改地址栏)
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.php -f
RewriteRule ^(.+)/?$ $1/index.php [L]

# 5. 全局无后缀访问(支持子目录,如/admin/meta → /admin/meta.php)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(en|de)/ [NC]  # 排除语言前缀路径
RewriteRule ^(.+)$ $1.php [L]

# 6. 语言前缀的无后缀访问(如/en/about → about.php?lang=en)
RewriteRule ^(en|de)/([^/.]+)$ $2.php?lang=$1 [L]

# 错误页面配置
ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 404 /error.php
ErrorDocument 405 /error.php
ErrorDocument 408 /error.php
ErrorDocument 410 /error.php
ErrorDocument 413 /error.php
ErrorDocument 414 /error.php
ErrorDocument 429 /error.php

ErrorDocument 500 /error.php
ErrorDocument 502 /error.php
ErrorDocument 503 /error.php
ErrorDocument 504 /error.php
ErrorDocument 505 /error.php

# 安全头配置
<IfModule mod_headers.c>
    Header set X-XSS-Protection "1; mode=block"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-Content-Type-Options "nosniff"
    Header set Referrer-Policy "same-origin"
</IfModule>

关键修改说明

  • 规则顺序调整:将index.php重定向规则移到最前面,先把所有带index.php的URL转成干净路径,避免后续规则触发循环。
  • 子目录无后缀规则优化:把原无后缀规则的匹配模式从^([^/.]+)$改为^(.+)$,同时添加排除条件避免干扰语言前缀路径,确保子目录下的/admin/meta能正确映射到/admin/meta.php。
  • 目录跳转规则优化:在目录匹配规则中添加/?,兼容带或不带末尾斜杠的请求,同时通过[L]标记终止后续规则,防止触发无后缀规则导致循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 09:56:20