将www重定向到非www网址

时间:2018-10-04 05:00:52

标签: c# asp.net iis url-rewriting

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

如果该网址为 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网址没有重定向到非www网址。

你能分享我在那儿做错了吗?

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

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

1 个答案:

答案 0 :(得分: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