Life Moves On

My Experience With Technology

Wednesday, December 10, 2008

Redirect http requests to https using javascript

Here is a function to redirect all http requests to https using client side javascript.
All requests are redirected to https://www.hostname



function redirectToSecure()
{


var curprot = new String(window.document.location.protocol); //get protocol
var curhost = new String(window.document.location.hostname); //get hostname

if ((curprot.indexOf("https")== -1) && (curhost.indexOf("www.")== -1)){
// if both 'https' & 'www' not present

document.location.href='https://www.'+document.location.hostname;

} else if((curprot.indexOf("https")== -1) && (curhost.indexOf("www.")!= -1)){
// if 'https' not present & 'www' present

document.location.href='https://'+document.location.hostname;

} else if((curprot.indexOf("https")!= -1) && (curhost.indexOf("www.")== -1)){
// if 'https' present & 'www' not present

document.location.href='https://www.'+document.location.hostname;

}


}

Labels: ,

0 Comments:

Post a Comment

<< Home