.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 tofile.phptoo). - 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
相关产品推荐
相关产品推荐

