Redirect a user from HTTP to HTTPS using JavaScript

Although a redirection is best done using your webserver or server-side code (for SEO purpose), here’s a simple way to redirect a page from Http to Https using JavaScript

<script type="text/javascript">
if
(window.location.protocol == "http:") {
var restOfUrl = window.location.href.substr(5);
window.location = "https:" + restOfUrl;
}
</script>

If you want to avoid the back button as a result of the redirection, check this post of mine

Redirect to a New Page using JavaScript without Back Button

If you are looking out for an ASP.NET solution, check these links:

Redirect from HTTP to HTTPS in ASP.NET

Permanent Redirect in ASP.NET 4.0 (SEO Perspective)






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Rina said...

thanks, bookmark it ...

Unknown said...

Oh thank you soooo much! works perfectly!