How to redirect non WWW to WWW in web.config

I'm tried here web.config redirect non-www to www

And tried:

<rule name="ensurewww" enabled="false" stopProcessing="true">
    <match url=".*" />
    <conditions>
         <add input="{CACHE_URL}" pattern="^(.+)://(?!www)(.*)" />
    </conditions>
    <action type="Redirect" url="{C:1}://www.{C:2}/{R:1}" redirectType="Permanent" />
</rule>

Result: 1. abc.com ---> www.abc.com True

Result 2. abc.com/a.aspx--->www.abc.com/a.aspx False

Result 3. abc/com/abc---->www.abc.com/abc False

Finally: I want to Result 2 and Result 3 is True

Upvotes: 1

Views: 1559

Answers (2)

Hakakou
Hakakou

Reputation: 562

This is my generic version. Note that this will also redirect any http to the https version. For example:

http://test.com  → https://www.test.com
https://test.com → https://www.test.com

Also note that I have added an exception for //localhost. This is because I use this code for my asp.net web application, and I don't want while developing to redirect http://localhost to http://www.localhost ...

<rule name="RedirectNonWwwToHttpsWww" stopProcessing="true">
  <match url=".*" />
  <conditions>
    <add input="{HTTP_HOST}" pattern="^www\." negate="true" />
    <add input="{HTTP_HOST}" pattern="^localhost" negate="true" />
  </conditions>
  <action type="Redirect" url="https://www.{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
</rule>

Upvotes: 1

HO&#192;NG LONG
HO&#192;NG LONG

Reputation: 459

Tried: IIS Redirect non-www to www AND http to https

<rule name="Force WWW and SSL" enabled="true" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAny">
          <add input="{HTTP_HOST}" pattern="^[^www]" />
          <add input="{HTTPS}" pattern="off" />
      </conditions>
      <action type="Redirect" url="https://www.obu.vn/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>

It will Redirect non www to www and http to https

Upvotes: 3

Related Questions