Our Blog

Merge redirect from non-www to www and secure connection in one URL rewriting rules to avoid many redirects

For SEO we need to maintain one URL to each page, to avoid several URLs that go to the same page and resulting into divided reports.

so we use the URL rewrite rules to redirect non-www to www by adding the below rule to the web.config file

<rule name="RedirectNonWwwToWww" stopProcessing="true">
  <match url="(.*)" />
  <conditions>
    <add input="{HTTP_HOST}" pattern="^domain.com$" />
  </conditions>
  <action type="Redirect" url="http://www.domain.com/{R:0}" redirectType="Permanent" />
</rule>

and use the below to redirect from http to https

<rule name="RedirectToHTTPS" stopProcessing="true"> <match url="(.*)" />
  <conditions>
    <add input="{HTTPS}" pattern="off" ignoreCase="true" />
  </conditions>
  <action type="Redirect" url="https://{SERVER_NAME}/{R:1}" redirectType="Permanent" />
</rule>

but this will result to 2 redirections if users request URL : "http://domain.com" format.
so to avoid that we can merge the both in one rule by the below:

<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.domain.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>

tags