0
votes

My goal is to redirect all www.* urls to non-www urls. For example:

If the url is www.mydomain.com/users it should redirect to mydomain.com/users.

In order to achieve that I have written the following code in my 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>

but it does nothing and I can see the www urls not redirecting to non www urls.

Can you share what I am doing wrong there?

Do note that I don't want to add any hard coded domain in that rule. I want to make it generic.

I need a generic solution where in my rule there is no where a hard coded domain and a hard coded protocol is present.

1
It is not, I need a rule without hardcoded domain and without hardcoded protocol.Raghav
@Raghav Please read all answers from the linked dupeSir Rufo

1 Answers

2
votes

Well, here is the solution I came up with.

I have provided the solution with all the details along with comments comments for the regex, capturing groups etc. used in the rule:

   <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>

It will do the following redirects:

   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