Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 243
user123457 Avatar asked Feb 11 '23 15:02

user123457


2 Answers

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>
like image 150
user123457 Avatar answered May 26 '23 11:05

user123457


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

like image 45
Amir Avatar answered May 26 '23 11:05

Amir