20-08-2010

Javascript detect or enforce http or https with JavaScript

Here's how you can enforce a redirect to a https ssl address when a page is accessed via http. Is ofcourse only effrective if they have JavaScript turned on. Works in frames as well

if(top.location.protocol=="http:"){
  top.location="https:"+top.location.href.substr(5);
}
 

It is better to do this uing location.replace if available to avoid the browser getting caught on a page and messing up the back button functionality:

if(top.location.protocol=="http:"){
	if (location.replace){ 
 		top.location.replace("https:"+top.location.href.substr(5));
	} else {
		top.location="https:"+top.location.href.substr(5);
	}
}
Keywords: ssl http https

Comments:

Your comment:

»

 

[x]