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

如何用.htaccess实现无后缀URL动态映射子目录文件并强制HTTP访问

解决方案

你只需要替换原有静态重写规则为带文件存在判断的动态规则即可,修改后的完整.htaccess代码如下:

RewriteEngine On

# 强制请求走HTTP
RewriteCond %{SERVER_PORT} 443
RewriteRule ^(.*)$ http://www.example.com.br/$1 [R=301,L]

RewriteBase /
RewriteCond %{HTTP_HOST} ^www.example.com.br
# 动态重写规则:判断directory目录下是否存在对应php文件,存在则执行内部重定向
RewriteCond %{DOCUMENT_ROOT}/directory/$1.php -f
RewriteRule ^([^/]+)$ directory/$1.php [L,QSA]

# 隐藏并跳转PHP后缀
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP/.+
RewriteRule ^(.+)\.php$ /$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/shtml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

规则说明

  • 新增的动态规则会自动捕获根目录下的第一层请求路径,先校验/directory/目录下是否存在同名的.php文件,仅当文件存在时才会执行内部重写,不会改变地址栏URL,也不会影响其他正常请求
  • 原有所有功能完全保留:强制HTTP访问、隐藏PHP后缀、gzip压缩均可正常使用
  • 后续往/directory/目录下新增PHP文件不需要修改.htaccess,直接访问http://www.example.com.br/文件名(无需带.php后缀)即可正常访问对应文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:36:01