【问题标题】:Remove trailing slash with htaccess with existing rules使用现有规则使用 htaccess 删除尾部斜杠
【发布时间】:2021-12-24 04:28:27
【问题描述】:

我希望在使用 htaccess 给出斜杠时删除斜杠。符合我现有规则的最佳方法是什么:

  # make sure www. is always there
  RewriteCond %{HTTP_HOST} !^www\.
  RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

  RewriteCond %{HTTPS} off
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
  
  # if requested url does not exist pass it as path info to index.php
  RewriteRule ^$ index.php?/ [QSA,L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule (.*) index.php?/$1 [QSA,L]

示例 URL 类似于:

https://www.example.com/this-test/

我当然希望去掉结尾的斜线。

我试过了:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R,L]

但这不适用于现有的规则。由于其他规则,它最终会重定向到 index.php 页面。

【问题讨论】:

  • 感谢您在问题中分享您的努力,请务必提及您在问题中点击的示例网址。
  • 添加了更多信息。
  • 您尝试在现有规则的哪个位置插入新规则?
  • 我在任何位置都试过了,但都无法正常工作。

标签: .htaccess url mod-rewrite trailing-slash


【解决方案1】:

这样吧:

Options -MultiViews
DirectoryIndex index.php
RewriteEngine On

# add www and turn on https in same rule
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(.+)/+$
RewriteRule ^ %1 [R=301,NE,L]

# if requested url does not exist pass it as path info to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?/$0 [QSA,L]

请务必在完全清除浏览器缓存后进行测试。

【讨论】:

  • 有趣。它非常接近,但奇怪的是,如果第一个“文件夹”的名称中有连字符,它最终会转到最后一条规则并将路径传递给 index.php?
  • RewriteCond %{REQUEST_URI} ^(.+)/+$ 中没有连字符检查,除了使用RewriteCond %{REQUEST_FILENAME} !-d 我们跳过所有真实文件夹。出于安全原因,真实文件夹应始终以/ 结尾。
  • 好吧,有了这条规则 "RewriteRule ^support-us/?$ /index.php?module=support_us [N]" 和你的建议它结束了 "/support-us?module=support_us " 而不是 "/support-us"。
  • 该规则不是我回答的一部分。 /support-us/ 是一个真实的目录吗?
  • 您需要编辑您的问题以包含所有重写规则。
猜你喜欢
  • 2022-01-23
  • 2011-12-09
  • 2015-01-15
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多