【问题标题】:.Net Url Rewrite to another domain with a specific path pattern.Net Url 使用特定路径模式重写到另一个域
【发布时间】:2017-10-10 14:47:18
【问题描述】:

我正在开发一个新站点来替换我的一个旧站点,我的目的是将一些旧站点链接重定向到备份服务器(我将保留旧站点一段时间,直到我想去掉所有的 url 路由)

例如,这里有一些旧链接 https://www.example.com/category/something/here

我希望我的新网站将上述网址重定向到 https://backup.example.com/category/something/here

我不擅长正则表达式,我尝试过类似的方法但不起作用,有什么想法吗? tks

    <rule name="Redirect URL" stopProcessing="true">
      <match url="^(.*)/category/(.*)" ignoreCase="true" />
      <action type="Redirect" url="http://backup.example.com/{R:0}" redirectType="Permanent" />
    </rule>

【问题讨论】:

  • 我会说,如果只是时间问题,您不应该进行永久重定向。
  • @RichardHubley - OP 说“我正在开发一个新站点来替换我的一个旧站点”。这意味着永久重定向是正确的方法。

标签: asp.net asp.net-mvc


【解决方案1】:

url 只能匹配路径。要匹配实际主机名,您需要使用{HTTP_HOST}

<?xml version="1.0"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Redirect www.example.com or example.com to backup.example.com" stopProcessing="true">
                    <match url="^category/(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^(www\.)?example.com$" />
                    </conditions>
                    <action type="Redirect" url="http://backup.example.com/category/{R:1}" redirectType="Permanent" />
                </rule>         
            </rules>
        </rewrite>
        <httpProtocol>
            <redirectHeaders>
                <!-- This is to ensure that clients don't cache the 301 itself - this is dangerous because the 301 can't change when put in place once it is cached -->
                <add name="Cache-Control" value="no-cache"/>
            </redirectHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

我还举了一个如何关闭 301 重定向缓存的示例。这可能会导致调试期间出现问题,因为浏览器会自行缓存 301 重定向,然后忽略您对此配置所做的任何更改,除非手动清除缓存。

参考资料:

【讨论】:

  • tks 回复,但如果我完全取出 R:0,只需使用 url="backup.example.com",它仍然不会重定向并在新站点上给我 404 错误
  • 不,它仍然停留在 www.example.com 并且因为它是新站点,所以我收到 404 错误。顺便说一句,www 和备份托管在两个单独的服务器上
  • 我正在使用您的第二个解决方案,匹配 url="^example.com/category(.*)" .. 但仍然不会重定向到备份域
  • @JoeLu - 我更正了答案。自从我这样做以来已经有一段时间了,我忘记了主机名不是 URL 的一部分。
  • tks 进行更正,好消息是我得到了重定向 :) 但重定向的 url 不保留“类别”部分,即 www.example.com/category/something/here被重定向到 backup.example.com/something/here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-24
  • 2019-07-02
  • 2021-10-22
  • 2019-04-09
  • 1970-01-01
  • 2016-11-27
  • 2020-03-26
相关资源
最近更新 更多