Search code examples
javascripthtmlforward

How to make a ssl forwarding script that runs once per page load


I have been having some trouble using a javascript script that automatically makes you get forwarded to use ssl. example,

http://www.example.com/link becomes https://www.example.com/link

But my issue is that is continuously loads the script, but I want it to stop when it is already loaded. It reloads continuously, making it very annoying and hard to click the links on the page.

Here is my current script

window.location = "https://" + window.location.hostname + window.location.pathname + window.location.search;


Solution

  • You need this:

    if(window.location.protocol == 'http:') {
        window.location = "https://" + window.location.hostname + window.location.pathname + window.location.search;
    }
    

    ...or even better:

    if(window.location.protocol == 'http:') {
        window.location.replace(window.location.toString().replace(/^http:/, 'https:'));
    }
    

    Second variant is better because:

    • URL may be complex and will be handled properly
    • Because of using window.location.replace() instead of directly assigning a string to window.location, previous URL will be removed from history and when user clicks 'back' button, he will jump to original page, not to the one with "http:" protocol: http://www.w3schools.com/jsref/met_loc_replace.asp

    But it's better to implement this on server side.