【问题标题】:Redirect if URL doesn't contain a string, keep rest of url intact如果 URL 不包含字符串,则重定向,保持 url 的其余部分不变
【发布时间】:2018-10-22 15:55:11
【问题描述】:

因此,我们尝试将旧的子域重定向到我们的新域,并保持 URL 的其余部分不变。我们正在尝试将其全部移至子目录。

使用以下方法很容易...

RewriteCond %{HTTP_HOST} ^test\.example\.com/$ [NC]
RewriteRule ^(.*)$ https://example.com/test-path/$1 [R=302,L]

但是,之前的一些网站 URL 实际上已经是 test.example.com/test-path/,所以我们希望这些 URL 不会在 /test-path/ 上加倍

该规则正在将 URL 变成这样...

test.example.com/test-path/some-page

进入

test.example.com/test-path/test-path/some-page

所以现在我们正在尝试以下...

RewriteCond %{REQUEST_URI} !/test-path/
RewriteCond %{HTTP_HOST} ^test\.example\.com/$ [NC]
RewriteRule ^(.*)$ https://example.com/test-path/$1 [R=302,L]

虽然这将重定向到 example.com/test-path/,但它现在正在丢失正常 URL 之后的任何内容。

test.example.com/test-path/other-path

被重定向到

example.com/test-path/

希望这对我们正在尝试做的事情有意义。将子域重定向到新域到子目录中,而不是加倍 request-url 目录。

编辑:

通过最近的尝试,它似乎根本不在乎 url 是否包含 /test-path/。无论如何它仍然会重定向。

【问题讨论】:

    标签: apache .htaccess redirect mod-rewrite


    【解决方案1】:
    RewriteCond %{HTTP_HOST} ^test\.example\.com/$ [NC]
    RewriteRule ^(.*)$ https://example.com/test-path/$1 [R=302,L]
    

    我认为这只是您的问题中的一个错字(?),但您的主机名末尾有一个错误的斜杠 - 这永远不会匹配。

    为避免在请求的 URL 上出现 /test-path 时重复,但仍重定向到 /test-path,您可以将其捕获为 可选 URL 路径,如果它匹配了。例如:

    RewriteCond %{HTTP_HOST} ^test\.example\.com [NC]
    RewriteRule ^(?:test-path/)?(.*) https://example.com/test-path/$1 [R=302,L]
    

    我已删除 CondPattern 上的斜杠和尾随 $,以便它匹配(并因此规范化)以点结尾的 FQDN。

    (?:test-path/)? 是一个捕获test-path/ 的非捕获组(因此不会创建反向引用)。然后,该组是可选的,带有尾随 ?


    旁白:

    RewriteCond %{REQUEST_URI} !/test-path/
    RewriteCond %{HTTP_HOST} ^test\.example\.com/$ [NC]
    RewriteRule ^(.*)$ https://example.com/test-path/$1 [R=302,L]
    

    如果/test-path/ 出现在请求的 URL 中的任何位置,则不会执行任何操作。因此,如果您看到重定向,那么看起来“其他东西”正在这样做!

    通过最近的尝试,它似乎根本不在乎 url 是否包含 /test-path/。无论如何它仍然会重定向。

    正如我所说,一定有别的东西在做这件事。可能与其他指令发生冲突?您是否混合了来自 mod_alias 和 mod_rewrite 的重定向?

    请注意,这些重定向应位于 .htaccess 文件的顶部。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      相关资源
      最近更新 更多