IIS Redirect www to non-www and http to https: is

2019-05-28 20:11发布

问题:

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?

回答1:

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.



回答2:

You should be able to with HTTP to HTTPS, the reverse is trickier depending on your IIS setup.

     <rule name="HTTP to HTTPs and www to non-www " enabled="true" stopProcessing="true">
         <match url="(.*)" />
         <conditions logicalGrouping="MatchAny" trackAllCaptures="false">
             <add input="{SERVER_PORT}" pattern="^80$" />
             <add input="{HTTP_HOST}" pattern="^www\.example\.com$" />
         </conditions>
         <action type="Redirect" url="https://example.com/{R:1}" />
     </rule>

Keep in mind, based on how you have sites structured in IIS (Bindings, sites, etc), it's all going to influence how your rewrite rules work and where your going to place them. At the app level or as a global rule.

Since I don't know how you have your bindings or IIS structured with other sites, It's impossible to write the URL Rewrite rule for you with 100% accuracy. So you might need to do a little experimentation with the above syntax.