Javascript: Auto Redirect to SSL page

symetrix dot net

SSL Detection

I did some searching and couldn’t turn up anything, so I decided to post this for anyone looking for something similar. Including this bit of JavaScript code into a header file of your website will cause all connections to be bounced over to an SSL secured version of your site. You can even use the same DocumentRoot for your secure and non-secure versions without problems.

<script language="javascript">
if (document.location.protocol != "https:")
{
document.location.href = "https://secure.you.tld" + document.location.pathname;
};
</script>

∞ Mon Dec 15th, 2:04pm

Comment

1. The only problem with this is that it wont work if someone doesnt have javascript. It makes security a sugestion, not a requirement. The same thing can be accomplished server side if you use apache with a mod rewrite rule.(though i imagine there must be a way to do it in IIS also).I think you would use the following(though this is off the top of my had, so it nay be wrong)*
RewriteRule http://(.*) https://$1

— jesse Wed Dec 31st, 8:14pm

4 thoughts on “Javascript: Auto Redirect to SSL page

    1. function redirectSecure()
      {
      if (document.location.protocol != “https:”){
      var oldURL = window.location.hostname + window.location.pathname+window.location.search;
      var newURL = “https://” + oldURL;
      window.location = newURL;
      }
      }
      redirectSecure();

  1. Sangam’s function works a little better for me in an app that has session IDs – it redirects and keeps the session. I don’t know why Amit’s initial script didn’t. Maybe –

    “https://secure.you.tld” + document.location.pathname

    doesn’t redirect the entire URL.

    Thanks,
    SM

    1. I also like the version suggested by Sangam. document.location is now deprecated and it is suggested to use window.location which is more portable.

      –Amit

Leave a Reply