【问题标题】:Apache RewriteRule for removing tailing slash only at rootApache RewriteRule 仅在根目录下删除尾斜线
【发布时间】:2014-06-26 06:00:57
【问题描述】:

我知道有很多关于 Apache RewriteRules 的问题,尤其是关于删除尾部斜杠的问题。我看了很多,但似乎找不到任何人试图解决这个问题。

我使用的是 Magento,所以 URL 结构如下所示:

  • example.com/index.php
  • example.com/index.php/
  • example.com/index.php/page1/

这是我理想的 URL 结构:

  • example.com
  • example.com/page1/
  • example.com/page2/

所以基本上我只想剥离 index.php 并确保裸域没有尾部斜杠(example.com 而不是 example.com/)。另外,如果可能的话,我不想包含硬编码的域名,以便可以在不同的环境中应用重写。

这是我目前的重写...

RewriteCond %{REQUEST_URI} ^/index\.php/?
RewriteRule ^index.php/(.*) /$1 [R=301,L]

这似乎适用于所有情况,除了:

  • example.com/index.php(根本不起作用)
  • example.com/index.php/(留下斜杠)

我将不胜感激任何正则表达式的建议!谢谢。


更新 感谢@zx81 的以下回答,我已成功将所有 URL 剥离到根域,但仍然无法删除斜杠。

这里是当前 URL:example.com/

而且我无法删除尾部斜杠!

【问题讨论】:

    标签: regex apache .htaccess magento mod-rewrite


    【解决方案1】:

    无法现场测试,但试试这个。

    RewriteRule ^index\.php()/?(?:([^/]+)/)? $1$2 [R=301,L]
    
    1. 由于空的捕获组 1 (),它应该处理根本不起作用的那个。
    2. 在 PCRE(Apache 的正则表达式风格)中,这也会去除尾部斜杠,但 Apache 可能会决定将其添加回来。

    【讨论】:

    • @mtaube 除了这个正则表达式来处理未重定向的路径之外,如果斜杠留在根部,您可能需要查看directory slash directive
    • 谢谢您,先生!你是对的,正则表达式确实会处理这条路径。我仍然无法弄清楚根域上的斜杠,Apache 根本不喜欢这个想法。但还没有放弃!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多