Redirect HTTP To HTTPS

Sometimes we need our own custom configuration setup to force the redirect request from HTTP to HTTPS. normally we need when someone tries to access our URL from a non-secure platform (HTTP) and we don’t want to access them and redirect on the secure layer (HTTPS).

To do that in this blow we will see how we can do that using the web.config file.

Open web.config file. (If you don’t have that file create that file with the same name and put inside root folder) and put below lined inside “<system.webServer>” tag.

<rewrite>
<rules>
<rule name="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>

If you need “Strict-Transport-Security” while using HTTPS, we need to put below outbound rules inside the web.config file below the rules tag inside the “rewrite” tag.

 <outboundRules>
    <rule name="Add Strict-Transport-Security when HTTPS enable" enabled="true">
        <match serverVariable="RESPONSE_Strict_Transport_Security"
            pattern=".*" />
        <conditions>
            <add input="{HTTPS}" pattern="on" ignoreCase="true" />
        </conditions>
        <action type="Rewrite" value="max-age=31536000" />
    </rule>
</outboundRules>

Now, when anyone comes to HTTP, it will automatically redirect to HTTPS.

I hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories