0

我的目标是将所有 www.* url 重定向到非 www url。例如:

如果 url 是www.mydomain.com/users它应该重定向到mydomain.com/users

为了实现这一点,我在 web.config 中编写了以下代码:

<rule name="Redirect www.* urls to non www" stopProcessing="true">
  <match url="*"  />
  <conditions>
    <add input="{HTTP_HOST}" pattern="^www$" />
  </conditions>
  <action type="Redirect" url="{HTTP_HOST}/{R:0}" redirectType="Permanent"/>
</rule>

但它什么也没做,我可以看到 www url 没有重定向到非 www url。

你能分享我在那里做错了什么吗?

请注意,我不想在该规则中添加任何硬编码域。我想让它通用。

我需要一个通用的解决方案,在我的规则中,没有硬编码域和硬编码协议存在。

4

1 回答 1

2

好吧,这是我想出的解决方案。

我已经为解决方案提供了所有详细信息以及规则中使用的正则表达式、捕获组等的注释:

   <rule name="Redirect www.* urls to non www" enabled="true">

      <!--Match all urls-->
      <match url="(.*)"/>

      <!--We will be capturing two groups from the below conditions. 
      One will be domain name (foo.com) and the other will be the protocol (http|https)-->

      <!--trackAllCaptures added for tracking Capture Groups across all conditions-->
      <conditions trackAllCaptures="true">

        <!-- Capture the host. 
        The first group {C:1} will be captured inside parentheses of ^www\.(.+)$ condition, 
        It will capture the domain name, example: foo.com. -->
        <add input="{HTTP_HOST}" negate="false" pattern="^www\.(.+)$"/>

        <!-- Capture the protocol.
        The second group {C:2} will be captured inside parentheses of ^(.+):// condition. 
        It will capture protocol, i.e http or https. -->
        <add input="{CACHE_URL}" pattern="^(.+)://" />

      </conditions>

      <!-- Redirect the url too {C:2}://{C:1}{REQUEST_URI}.
      {C:2} captured group will have the protocol and 
      {C:1} captured group will have the domain name.
      "appendQueryString" is set to false because "REQUEST_URI" already contains the orignal url along with the querystring.
      redirectType="Permanent" is added so as to make a 301 redirect. -->

      <action type="Redirect" url="{C:2}://{C:1}{REQUEST_URI}" appendQueryString="false" redirectType="Permanent"/>
    </rule>

它将执行以下重定向:

   http://www.foo.com -> http://foo.com

   https://www.foo.com -> https://foo.com

   http://www.foo.com?a=1 -> http://foo.com?a=1

   https://www.foo.com?a=1 -> https://foo.com?a=1
于 2018-10-04T05:53:13.510 回答