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

.htaccess实现带/不带尾斜杠的目录URL隐式转发至文件

Fix .htaccess for Clean Directory-style URLs Without Address Bar Jumps

Looks like you're running into the classic mod_dir vs mod_rewrite conflict here! The issue with your current setup is that Apache's default mod_dir module is interfering when you access URLs without a trailing slash—it automatically sends a 301 redirect to add the slash, which breaks the clean internal rewrite you want. Here's the fixed .htaccess code and a breakdown of what's changed:

Fixed .htaccess Code

RewriteEngine On
RewriteBase /
Options +FollowSymLinks

# Disable automatic trailing slash redirects for directories
DirectorySlash Off

# Force HTTPS (keep your existing exclusion for "activate" URI)
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !activate [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Handle both trailing slash and non-trailing slash requests
# Skip real files and directories to avoid interfering with actual content
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /file.php?folder=$1 [L]

Key Changes Explained

  • DirectorySlash Off: This is the critical fix. By default, Apache automatically redirects requests for directories (like /myfolder) to the trailing slash version (/myfolder/) via a 301. Turning this off stops that external redirect, letting our rewrite rule handle both URL formats internally without changing the address bar.
  • Added RewriteCond %{REQUEST_FILENAME} !-d: Your original rule only skipped real files, but not real directories. Adding this ensures we don't rewrite requests for actual directories on your server (remove this line if you want to forward real directories to file.php too).
  • Preserved your HTTPS redirect: Kept your existing logic to force HTTPS, excluding the "activate" URI as you had before.

Testing It Out

Now when users visit either https://www.example.com/myfolder or https://www.example.com/myfolder/, the address bar stays exactly as they typed it, while Apache internally loads https://www.example.com/file.php?folder=myfolder behind the scenes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:27:33