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

HTaccess配置:实现HTTPS、域名统一及URL末尾斜杠规范

问题说明

当前已成功移除URL的.php扩展名,但同一子页面可通过两种方式访问:不带末尾斜杠的www.example.com/thema和带末尾斜杠的www.example.com/thema/。现有.htaccess配置如下:

DirectoryIndex index.php

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    RewriteCond %{HTTP_HOST} !^www\.example\.com$
    RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

    # redirect file.php to /file/
    RewriteCond %{THE_REQUEST} \s/+(\.+?)\.php\s [NC]
    RewriteRule ^ /%1/ [R=302,NE,L]

    # added .php extension to /file by checking presence of file.php
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^(\.+?)/?$ $1.php [L]
</IfModule>

需要调整配置满足以下要求:

  • 域名仅通过HTTPS访问;
  • 首页仅可通过www.example.com(不带末尾斜杠)访问;
  • 子页面仅可通过带末尾斜杠的URL(如www.example.com/thema/)访问。

修改后的.htaccess配置
DirectoryIndex index.php

<IfModule mod_rewrite.c>
    RewriteEngine On

    # 强制HTTPS+www访问,避免多次跳转
    RewriteCond %{HTTPS} !=on [OR]
    RewriteCond %{HTTP_HOST} !^www\.example\.com$
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]

    # 首页:移除末尾斜杠(仅针对根目录)
    RewriteCond %{REQUEST_URI} ^/$
    RewriteRule ^(.*)/$ $1 [L,R=301]

    # 子页面:强制添加末尾斜杠(排除实际文件和根目录)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^/$
    RewriteRule ^(.*[^/])$ /$1/ [L,R=301]

    # 将file.php永久重定向到/file/
    RewriteCond %{THE_REQUEST} \s/+([^.]+)\.php\s [NC]
    RewriteRule ^ /%1/ [R=301,NE,L]

    # 为请求映射.php扩展名(仅当对应文件存在时)
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^([^/]+)/?$ $1.php [L]
</IfModule>

关键调整说明
  • 合并HTTPS与www规则:把原有的两条跳转规则合并,避免用户访问非www或HTTP地址时产生多次跳转,直接统一跳转到https://www.example.com开头的地址。
  • 首页斜杠控制:专门针对根目录请求,若访问www.example.com/会自动301重定向到不带斜杠的www.example.com。
  • 子页面强制加斜杠:排除实际存在的文件和根目录,所有子页面请求如果不带末尾斜杠,会被301重定向到带斜杠的版本。
  • 修正.php重定向逻辑:把原规则中的(\.+?)替换为([^.]+)避免匹配错误,同时将临时重定向R=302改为永久重定向R=301,更利于SEO优化。
  • 保留扩展名映射:保留原有的根据文件存在性自动添加.php扩展名的逻辑,同时兼容带/和不带/的请求(但子页面会先被强制跳转到带/的版本)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:46:15