01 November 2008

Enforcing SSL Security For WebPages

Many times we need to add SSL security to few of our web pages for secure transactions.
Now initailly when i wanted to do so i tried to hard code the link by using "https://mylink.com ". But if the user typed the link as "http://mylink.com" the page still opened in non secure mode.
To overcome this problem i found a simple function that automatically detects if the page is in secure mode or not and then force it to go into secure mode.

Here is the code for ASP.NET 2.0:

protected void ForceHTTPS()
string server_name=HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]);
string forceurl="https://"+ server_name + Request.FilePath;

and for PHP 5:

function ForceHTTPS()

These can be very handy when only a few web pages need SSL.
Note: Please make sure that the server has a valid SSL certificate( need to purchase) for https:// to work other wise you will get page not found error or certificate expired error.

1 comment:

Anonymous said...

Thanks! I never liked the exception my login class would throw if SSL was needed and wasn't used, I think it's better to just redirect them to the https:// link.