HTTPS redirect with web.config

If you configure HTTP to HTTPS redirection from the IIS console, it will get overwritten by the web.config form a published application. Here is how to configure http to https redirection isde your project web.config.

  <system.webServer>
    <rewrite>
      <rules>
        <rule name="HTTPS Redirect" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="^OFF$" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

We can also add non-www to www redirection, by using the setup below:

    <rewrite>
      <rules>
        
        <rule name="HTTPS Redirect" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="^OFF$" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
        </rule>

        <rule name="WWW Redirect" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{CACHE_URL}" pattern="^(.+)://(?!www)(.*)" />
          </conditions>
          <action type="Redirect" url="{C:1}://www.{C:2}" redirectType="Permanent" />
        </rule>

      </rules>
    
    </rewrite>