ASP.NET MVC

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.

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago