JavaScript to redirect to https

by martin 22. July 2009 21:41

First off, you should never use JavaScript as a security enforcement mechanism, but you can use it within your server's "HTTPS required" error page to automatically (and easily) redirect your viewers to the proper secure page.

So first, configure IIS or Apache to "Require SSL".  This will automatically take all users that attempt to target a non HTTPS url to your servers configured 403 (or 403.4) error page.  Now go edit that error page (my IIS 7 error page was located at C:\inetpub\custerr\en-US\403.htm; for IIS 6 it was C:\WINDOWS\Help\iisHelp\common\403-4.htm) and add something like this:

<script type="text/javascript">

//<![CDATA[

function RedirNonHttps() {

    if (location.href.indexOf("https://") == -1) {

        location.href = location.href.replace("http://", "https://");

    }

}

//]]>

</script>

Then, simply call the RedirNonHttps function on page load :

<body onload="RedirNonHttps();" >

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

JavaScript

Comments

Add comment


(Will show your Gravatar icon)  

biuquote
  • Comment
  • Preview
Loading



Welcome

Please contact me if you have a great idea for a project and need technical expertise in designing, developing, or integrating a custom software solution. 

Recent Comments

Comment RSS