【问题标题】:htaccess Redirect or Rewrite URL - adding a segment to the URL without causing an infinite loophtaccess 重定向或重写 URL - 将段添加到 URL 而不会导致无限循环
【发布时间】:2021-02-11 05:25:07
【问题描述】:

我有一个 URL,我需要在其中添加一个段 /#!/

这不起作用,因为我得到了一个循环。

Options +FollowSymLinks
RewriteEngine On
RedirectMatch "/constantsegment/(.*)" "/constantsegment/#!/$1"

例如,假设我的网址是http://example.com/constantsegment/changeablesegment。我需要将网站重定向到http://example.com/constantsegment/#!/changeablesegment

请注意,在constantsegmentchangeablesegment 之间有一个名为#! 的URL 段(文件夹)。

我遇到的问题是在尝试将/#!/ 附加到/constantsegment/ 时创建了一个重定向循环。我怎样才能将/#!/ 添加到末尾,然后添加所有其他段。

再次

http://example.com/constantsegment/changeablesegment

应该重定向到

http://example.com/constantsegment/#!/changeablesegment

另一个例子(在这种情况下产品是常量段)

http://example.com/products/cars/blue

应该重定向到

http://example.com/products/#!/cars/blue

【问题讨论】:

    标签: .htaccess url redirect mod-rewrite url-rewriting


    【解决方案1】:
    RedirectMatch "/constantsegment/(.*)" "/constantsegment/#!/$1"
    

    只需将.* 更改为.+(1 个或多个)即可避免匹配目标 URL 并导致重定向循环。因为在重定向请求时,片段标识符没有传回服务器。

    您也可以通过捕获第一个“恒定”路径段来避免重复。例如:

    RedirectMatch "/(constantsegment)/(.+)" "/$1/#!/$2"
    

    请注意,上面的 mod_alias 指令(即RedirectMatch)与 mod_rewrite(即RewriteEngine On)无关。这里也不需要Options FollowSymLinks。除非您在 .htaccess 文件的其他地方使用 mod_rewrite。

    如果您已经将 mod_rewrite 用于其他重定向,那么您可能应该使用 mod_rewrite(即RewriteRule)来代替(以避免意外冲突)。例如:

    Options FollowSymLinks
    RewriteEngine On
    
    RewriteRule ^(constantsegment)/(.+) /$1/#!/$1 [NE,R,L]
    

    NE 标志是必需的,以防止 #(哈希)被 URL 编码并被视为 URL 路径的一部分。

    请注意,所有这些重定向都是 302(临时)。

    【讨论】:

    • 这是很好的解释,非常适合新学习者感谢您的分享,干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2013-01-25
    • 2013-12-12
    • 1970-01-01
    相关资源
    最近更新 更多