简体   繁体   中英

web.config redirect non-www OR non-https to https://www using rules

I need to redirect all non-www or non-https traffic to https://www using rule in web.config

http://domain.com --> https://www.domain.com
http://www.domain.com --> https://www.domain.com
https://domain.com --> https://www.domain.com

I modified rules from Web.config. Redirect all traffic to www.my... Using rules element. but it fails to redirect http://www.domain.com to https://www.domain.com .

    <rewrite>
        <rules>
            <clear />
            <rule name="Redirect to www subdomain">
                <match url=".*" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" negate="true" />
                    <add input="{SERVER_PROTOCOL}" pattern="^(.*)(/.*)?$"/>
                </conditions>
                <action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" redirectType="Permanent"/>
            </rule>
        </rules>
    </rewrite>

This will redirect all non www or non https to https://www

<rewrite>
  <rules>
    <rule name="non-www-https to www https" enabled="true" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^[^\.]+\.[^\.]+$" />
        <add input="{HTTPS}" pattern="on" />
        <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
      </conditions>
      <action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" />
    </rule>

  </rules>

</rewrite>

I added this line to ignore it on IIS express (local host):

<add input="{HTTP_HOST}" pattern="localhost" negate="true" />

The other advantage of this is that you do not need to enter your domain in this rule.

You can read more here: http://weblogs.asp.net/owscott/redirecting-non-www-to-domain-equivalent

I found the answer, i think it would help others if i post it here.

    <rewrite>
        <rules>
            <clear />
            <rule name="Redirect non-www OR non-https to https://www">
                <match url=".*" />
                <conditions logicalGrouping="MatchAny">
                    <add input="{HTTP_HOST}" pattern="^domain.com$" />
                    <add input="{HTTPS}" pattern="off" />
                </conditions>
                <action type="Redirect" url="https://www.domain.com/{R:0}" redirectType="Permanent"/>
            </rule>
        </rules>
    </rewrite>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM