.htaccess重定向时如何移除URL末尾斜杠?
解决重定向时URL末尾自动添加斜杠的问题
嘿,我明白你遇到的困扰了——用Redirect指令重定向后,目标URL总是多了个末尾斜杠,这确实烦人。咱们一步步来解决它:
为什么会出现这个问题?
主要有两个核心原因:
- Apache的
mod_dir模块默认会给服务器上真实存在的目录自动添加末尾斜杠(因为要加载目录索引文件,比如index.php),如果你的重定向目标对应一个真实目录,这个模块就会自动补全斜杠。 Redirect是mod_alias模块的指令,匹配逻辑相对宽泛,容易和mod_dir的规则冲突,导致意外的斜杠添加。
解决方案:用RewriteRule替代Redirect(更精准控制)
mod_rewrite的RewriteRule比Redirect灵活得多,能精准控制URL格式,避免自动加斜杠的问题。
1. 修改单个重定向规则
把你原来的:
Redirect /contact example.com/page
替换成:
RewriteRule ^contact$ http://example.com/page [L,R=301]
^contact$是精确匹配/contact路径(开头的^和结尾的$确保不会匹配带斜杠的/contact/)[L,R=301]表示这是最后一条执行规则(L),并返回301永久重定向(临时重定向可改用R=302)- 务必加上协议(http://或https://),否则可能导致相对路径错误
2. 全局移除所有非目录URL的末尾斜杠(可选)
如果你想让整个站点的非目录URL都去掉末尾斜杠,可以在RewriteEngine on之后添加以下规则:
# 排除真实存在的目录(避免影响目录正常访问) RewriteCond %{REQUEST_FILENAME} !-d # 匹配所有带末尾斜杠的URL,去掉斜杠 RewriteRule ^(.*)/$ /$1 [L,R=301]
这条规则会把类似/contact/的URL重定向到/contact,但不会影响真实目录的访问。
结合你的完整.htaccess代码调整
把所有Redirect规则替换成RewriteRule,并把全局去斜杠规则放在合适位置。调整后的代码大致如下:
# All explanations you could find in .htaccess.sample file RewriteEngine on # 全局移除非目录URL的末尾斜杠 RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # 替换原Redirect为RewriteRule RewriteRule ^configurator\.html$ /box.html [L,R=301] RewriteRule ^catalog/category/view/s/blog/id/9$ http://www.example.nl/blog [L,R=301] RewriteRule ^contact/index/$ http://www.example.com/contact.html [L,R=301] RewriteRule ^contact\.html/post$ http://www.example.com/contact.html [L,R=301] RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteCond %{REQUEST_METHOD} ^TRAC[EK] RewriteRule .* - [L,R=405] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule .* index.php [L] DirectoryIndex index.php <IfModule mod_php5.c> php_value memory_limit 768M php_value max_execution_time 18000 php_flag session.auto_start off php_flag suhosin.session.cryptua off </IfModule> <IfModule mod_php7.c> php_value memory_limit 768M php_value max_execution_time 18000 php_flag session.auto_start off php_flag suhosin.session.cryptua off </IfModule> <IfModule mod_security.c> SecFilterEngine Off SecFilterScanPOST Off </IfModule> <IfModule mod_ssl.c> SSLOptions StdEnvVars </IfModule>
注意:所有RewriteRule要放在RewriteEngine on之后、其他规则之前,确保优先级正确。
测试注意事项
- 修改
.htaccess后,记得清空浏览器缓存再测试(301重定向会被浏览器缓存,旧缓存可能影响结果) - 如果目标URL是服务器上的真实目录,去掉斜杠可能导致403错误,所以全局规则里的
RewriteCond %{REQUEST_FILENAME} !-d很关键,它会跳过真实目录的处理。
内容的提问来源于stack exchange,提问作者naknak12




