Friday, February 4, 2011

How to Configure SSL on Particular Pages of an IIS 7 Website

Today I wanted to force SSL on selected pages of a Website which is hosted in IIS 7. I could find lot of articles in the Web describing how to configure SSL for the whole website. But I needed it for few specific pages only. This is the way finally I achieved my goal.

Using Server Certificates feature of the IIS server install my certificate.
Create a SSL Binding for my Web site and make sure all the pages are accessible via both HTTP and HTTPS.

Then in order to force SSL on selected pages I used following method on Page_Load event of those pages. In here I used Request.ServerVariables collection to see if the protocol being used is HTTP or HTTPS.


protected void Page_Load(object sender, EventArgs e)
{
// Redirect to the corresponding secure page.
RedirectToSecurePage();
}




///
/// Redirect to the corresponding secure page.
/// Assumption: IIS web site is configured in port 80.
///

public void RedirectToSecurePage()
{
var httpsMode = string.Empty;
var serverName = string.Empty;
var url = string.Empty;

for (var i = 0; i < Request.ServerVariables.Keys.Count; i++)
{
var key = Request.ServerVariables.Keys[i];
if (key.Equals("HTTPS"))
{
httpsMode = Request.ServerVariables[key];
}
else if (key.Equals("SERVER_NAME"))
{
serverName = Request.ServerVariables[key];
}
else if (key.Equals("URL"))
{
url = Request.ServerVariables[key];
}
}
if (httpsMode.Equals("off"))
{
Response.Redirect(string.Concat("https://", serverName, url));
}
}


So when each page is browsed, the code that is contained in the Page_Load event detects if HTTP is used. If HTTP is used, the browser will be redirected to the same page by using HTTPS.

Comments are really appreciated on how to handle this scenario in another (better) way...