Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET: best practice for redirecting to https

I am working on a project that has one page that needs to make use of the SSL certificate. All of the links in the site to this page make use of https instead of http, but in the case that a user may navigate directly to the page I want the http version of the page to redirect to itself but use https.

I can do a Response.Redirect in the page_load event. I can write javascript that will update the location.href which will cause the postback. I'm sure there are more ways to skin this cat.

My question is, what is the best practice for an ASP.NET site on IIS 6 or 7 to redirect an http page to https? Is there a best practice or are all alternatives equal?

like image 425
Justin C Avatar asked Dec 16 '09 20:12

Justin C


People also ask

Is it OK to redirect HTTP to HTTPS?

If you are using the popular Apache Web server, you can easily redirect all traffic from unsecured HTTP to HTTPS. When a visitor goes to your site will be redirected to the secure HTTPS protocol. The server must allow you to use module mod_rewrite, but it's not a problem for most webhosting providers.


2 Answers

I'd use URL rewriting to do that. Why? because it's simple to implement, requires no modifications to the application, and is easy to maintain.

On IIS7 you can accomplish that using URL rewrite module, for example:

<!-- http:// to https:// rule -->
<rule name="ForceHttpsBilling" stopProcessing="true">
  <match url="(.*)billing/(.*)" ignoreCase="true" />
  <conditions>
    <add input="{HTTPS}" pattern="off" ignoreCase="false" />
  </conditions>
  <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}{REQUEST_URI}" />
</rule>

On IIS6 you'll have to use a 3rd party library. I use IIRF (http://www.codeplex.com/IIRF) it's free, stable, and has a good amount of features.

like image 107
Ariel Avatar answered Oct 01 '22 04:10

Ariel


Actually the best practice would be to do this in one of three places, assuming hardware or IIS settings are not an option. Just code options.

  1. In an HTTPModule. HttpModules are ran before any request is processed, so you could do the URL check and redirect there. This is what I would do.
  2. In Global.asax.
  3. In a custom base page, in the init function.

All of those would be good options. One and two are guaranteed to be hit by every request processed by ASP.NET. The third one requires that you make sure all of your pages inherit from the base page.

I would not put the code in each page, that's just bad programming.

Let me know if you need more clarification, but this is a good start.

like image 28
Clarence Klopfstein Avatar answered Oct 01 '22 03:10

Clarence Klopfstein