Search code examples
http-redirectiishttpsseo

IIS Redirect www to non-www and http to https: is it possible to do it with only one Redirect?


I need to avoid the double redirect I have after I created two IIS URL Rewrite rules to do:

1) Redirect www to non-www.

2) Redirect HTTP to HTTPS.

This is my code:

<rule name="Redirect to https" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
</rule>
<rule name="CanonicalHostNameRule1" enabled="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTP_HOST}" matchType="Pattern" pattern="^mydomain\.com$" ignoreCase="true" negate="true" />
    </conditions>
    <action type="Redirect" url="https://ABC/{R:1}" />
</rule>

(ABC is mydomain.com name but I had to change it in order to be able to post the question)

The problem is that if I go to www it does two redirects, one from www to non-www and a second one from http to https.

I also tried having only one rules with both conditions but the result was not better.

Is there a way to only do one redirect?


Solution

  • This is the final configuration I used:

             <rewrite>
                <rules>
                    <rule name="Force non-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://yourdomainname.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
                    </rule>
                </rules>
            </rewrite>
    

    It's only one rule that redirects to non-www and https url.