【问题标题】:Get .NET RewriteMap to work for old URL with or without trailing slash让 .NET RewriteMap 适用于带有或不带有斜杠的旧 URL
【发布时间】:2017-07-04 12:16:34
【问题描述】:

我在 web.config 文件中使用 RewriteMap 来 (301) 将旧 URL 重定向到新 URL。目前规则如下:

    <rule name="Localhost Rewrite Rules" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^(.*\.)?example\.com$" />
        <add input="{lhRewrites:{REQUEST_URI}}" pattern="(.+)" />
      </conditions>
      <action type="Redirect" appendQueryString="false" url="{C:1}" redirectType="Permanent" />
    </rule>

请注意,该模式有意对域进行硬编码,因为这是特定于每个域名的更大规则集的一部分。所以我一般不打算优化或重写(请原谅双关语)规则。

rewriteMap.config 文件包含以下重定向:

<rewriteMap name="lhRewrites">
  <add key="/old" value="/new" />
</rewriteMap>

目前,当我访问 http://example.com/old 时,该规则运行良好 - 它重定向到 http://example.com/new

但是,当“旧”URL 包含尾部斜杠时,它不起作用,即http://example.com/old/。无论旧 URL 上是否存在斜杠,我都需要它工作。

我希望不必复制所有映射键。

非常感谢。

【问题讨论】:

    标签: .net redirect web-config url-rewrite-module rewritemap


    【解决方案1】:

    如果您在正则表达式^(.*[^/])(\/?)$ 中匹配不带斜杠的 URL,然后将此匹配的 URL 传递到重写映射中,则可以实现它。你的规则应该是这样的:

    <rule name="Localhost Rewrite Rules" stopProcessing="true">
      <match url="^(.*[^/])(\/?)$" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^(.*\.)?example\.com$" />
        <add input="{lhRewrites:/{R:1}}" pattern="(.+)" />
      </conditions>
      <action type="Redirect" appendQueryString="false" url="{C:1}" redirectType="Permanent" />
    </rule>
    

    【讨论】:

    • 是否有理由使用^(.*[^/])(\/?)$ 而不仅仅是^(.*[^/])/?$
    • (.*[^/]) 用于match url 对我有用,并且可以处理多个尾部斜杠。
    猜你喜欢
    • 2021-04-07
    • 1970-01-01
    • 2015-09-20
    • 2013-08-24
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 2015-03-06
    • 2016-07-09
    相关资源
    最近更新 更多