Anuya
Anuya

Reputation: 8350

Redirecting the whole site to HTTPS in ASP.net application

I have done a project using asp.net and is ready to go live. Now the management has decided to use SSL for some reasons and hence the site should load in HTTPS.

Since the project is quite big, and it will be painful to check the URL and redirect it to HTTPS in all the pages, Is there a simple way where I can handle this globally or in my master pages ?

So, even if the website URL is typed with HTTP, it should be redirected to HTTPS site. How can I achieve this ?

Upvotes: 0

Views: 2232

Answers (2)

Linus Caldwell
Linus Caldwell

Reputation: 11078

If you don't want to control it per IIS like Nate suggested, you can simply do the redirection in your global.asax:

void Application_BeginRequest(Object sender, EventArgs e)
{
    if (Request.Url.Scheme != "https")
        Response.Redirect("https://yoursite.com");
}

May not be the most witty solution, but it does the job.

Upvotes: 0

Nate Hekman
Nate Hekman

Reputation: 6657

The general approach I use with IIS6 is to use the site properties in IIS to force SSL; that will generate a 403 error for anyone accessing the site on port 80, so next you register a custom aspx page to handle the 403 error and make it redirect the user to the secure site.

  1. Go to the Properties for your site (in IIS), Directory Security, click Edit by Secure communications, and Require secure channel (SSL). That now forces SSL for the entire site. If you visit the site now you should get the 403;4 error.
  2. Go to the Custom Errors tab, select the 403;4 error, and set it to a URL on your site (e.g., /403.4.aspx)
  3. Create this 403.4.aspx page. At its simplest it could be just Response.Redirect("https://www.mydomain.com"), but nicer would be something that redirects to the correct page and maintains any query strings. I don't have a dev environment at the moment to test this, but I think it would be something like this:

    Response.Redirect( "https://" + Request.ServerVariables("HTTP_HOST") + Request.ServerVariables("URL") );

  4. Back in IIS, set the properties on this 403.4.aspx page so it does NOT require a secure channel.

Now when someone tries to access any page of your site, IIS will send them to the 403.4.aspx page, which will redirect them to the secure site.

Upvotes: 1

Related Questions