There are tones of blog post out there on how to redirect http to https. As in when a user request for http://myserver.com/Login.aspx
they will be redirected to https://myserver.com/Login.aspx
One can do it with IIS but I find that way a bit ugly since you have to create another site and set the 403 to redirect to another location. Not as elegant as apache mod rewrite.
A more elegant approach I found when using asp .net is by using an HttpModule in your code, so that the entire site is redirected. There are other solutions to redirect individual pages but for this post we will focus on redirecting all traffic to SSL.
To begin with we will code up an RedirectToSSL.cs page and place it into our App_Code folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
using System; using System.Web; namespace SolutionName.App_Code { public class RedirectToSSL : IHttpModule { #region IHttpModule Members public void Dispose() { } public void Init(HttpApplication context) { context.BeginRequest += ContextBeginRequest; } private static void ContextBeginRequest(object sender, EventArgs e) { HttpApplication application = sender as HttpApplication; if (application == null) return; if (application.Request.IsSecureConnection) return; // send user to SSL string serverName = HttpUtility.UrlEncode(application.Request.ServerVariables["SERVER_NAME"]); string filePath = application.Request.FilePath; application.Response.Redirect("https://" + serverName + filePath); } #endregion } } |
Then all we have to do is add this line in our web.config file in order to enable it.
1 2 3 |
<httpModules> <add name="RedirectToSSL" type="SolutionName.App_Code.RedirectToSSL"/> </httpModules> |
Replace the solutionName with your project name and voila you now have the entire site in SSL and you don’t have to worry about talking to an admin for IIS configuration or anything like that.