360

Is there any way to detect HTTP or HTTPS and then force usage of HTTPS with JavaScript?

I have some codes for detecting the HTTP or HTTPS but I can't force it to use https: .

I'm using the window.location.protocol property to set whatever the site is to https: then refresh the page to hopefully reload a new https'ed URL loaded into the browser.

if (window.location.protocol != "https:") {
   window.location.protocol = "https:";
   window.location.reload();
}
5
  • 21
    This is far more reliably (and efficiently) handled server side.
    – Quentin
    Apr 5, 2012 at 21:09
  • 3
    I think you are right. As an attacker using a MITM attack, I could just delete this code. So it offers only protection against passiv attacks.
    – ndevln
    Jan 20, 2014 at 18:44
  • The detection part is a duplicate of How can I use JavaScript on the client side to detect if the page was encrypted? from 2008. Jul 13, 2015 at 21:35
  • 1
    @NeoDevlin a MITM attacker on http can replace a server side redirect as well Mar 10, 2017 at 23:50
  • 1
    Exactly. In 2018, there is no excuse not to use HSTS. This is the only safe way to force HTTPS.
    – user6269864
    Mar 13, 2018 at 10:10

13 Answers 13

598

Try this

if (location.protocol !== 'https:') {
    location.replace(`https:${location.href.substring(location.protocol.length)}`);
}

location.href = blah adds this redirect to the browser history. If the user hits the back button, they will be redirected back to the the same page. It is better to use location.replace as it doesn't add this redirect to the browser history.

14
  • 3
    Why window and not document?
    – webjay
    Dec 19, 2013 at 16:16
  • 6
  • 11
    Should the string comparison be !==?
    – Wes Turner
    Oct 12, 2014 at 14:06
  • 5
    @WesTurner It shouldn't matter either way. They're both always going to be strings. If one was a number or a boolean, then it might make a difference.
    – Soumya
    Oct 14, 2014 at 3:53
  • 20
    location.replace(url) would be much better than location.href = url for this case. You don't want this redirection in the browser's history or the user hitting the back button just to get redirected again. Jul 27, 2018 at 17:36
74

Setting location.protocol navigates to a new URL. No need to parse/slice anything.

if (location.protocol !== "https:") {
  location.protocol = "https:";
}

Firefox 49 has a bug where https works but https: does not. Said to be fixed in Firefox 54.

3
  • 2
    if window.location.href.match('http:') window.location.href = window.location.href.replace('http', 'https') works on latest FF and Chrome. Dec 4, 2013 at 8:14
  • 2
    location.protocol = "https"; seems to work though in firefox 28 Apr 28, 2014 at 16:33
  • 2
    Crap that breaks the back button. Use location.replace instead. Apr 21, 2019 at 21:59
25

It is not good idea because you just temporary redirect user to https and browser doesn't save this redirect.

You describe task for web-server (apache, nginx etc) http 301, http 302

5
  • 3
    agree. Forcing https on server is far more reliable Aug 17, 2012 at 8:07
  • 3
    I could see it being used if preserving the hash value is important. It is not sent to the server and some browsers do not preserve it.
    – Jason Rice
    Oct 3, 2013 at 0:22
  • Here's a link to Set Azure Web Site for https only ... blogs.msdn.com/b/benjaminperkins/archive/2014/01/07/…
    – OzBob
    May 15, 2015 at 1:55
  • 1
    Not necessarily true. There is a school of thought that 301 is the devil for caching reasons. getluky.net/2010/12/14/301-redirects-cannot-be-undon
    – fivedogit
    Mar 3, 2016 at 15:03
  • 2
    While it's true that it's generally not a good idea to do this client side, this is not what was asked. And you do not show how to do it, hence this is not an answer. Also, in these days of static webpages, often there is no way to do this server side (think Github pages), meaning you have to do this on the client. Still, you can help improve the search by adding canonical link tags to avoid people hitting the non-ssl version.
    – oligofren
    Dec 28, 2018 at 14:26
17
if (location.protocol == 'http:')
  location.href = location.href.replace(/^http:/, 'https:')
0
16

How about this?

if (window.location.protocol !== 'https:') {
    window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}

Ideally you'd do it on the server side, though.

2
  • 1
    it's missing the port
    – eadmaster
    Jan 12, 2018 at 13:44
  • and search / query string also Jan 18, 2021 at 8:04
12

You should check this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

Add this meta tag to your index.html inside head

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

Hope it helped.

2
  • Much more elegant solution when you do not have control of the code being sun on the page (html from a db for instance). We had a gravatar insecure connection and this solved everything.
    – ransems
    Jun 25, 2020 at 9:25
  • 1
    Works great, with one minor caveat--on the very first load the index page is left on http and not reloaded until you navigate again. Tested in incognito mode. It was a problem for my single page front-end which was CORS blocked as it was not immediately on HTTPS. Apr 18, 2022 at 20:48
5

Not a Javascript way to answer this but if you use CloudFlare you can write page rules that redirect the user much faster to HTTPS and it's free. Looks like this in CloudFlare's Page Rules:

enter image description here

1
  • I actually found this very useful, not for answering the question as framed, but for providing useful information about a possibly more reliable way for a SaaS service that does not offer always-on SSL.
    – MrMesees
    Apr 11, 2016 at 9:07
4

You can do:

  <script type="text/javascript">        
        if (window.location.protocol != "https:") {
           window.location.protocol = "https";
        }
    </script>
1
  • It works. Is it a standard way to redirect? will it work in all browsers?
    – mahfuz
    Nov 12, 2019 at 18:14
4

I like the answers for this question. But to be creative, I would like to share one more way:

<script>if (document.URL.substring(0,5) == "http:") window.location.replace('https:' + document.URL.substring(5));</script>
3

The below code assumes that the variable 'str' contains your http://.... string. It checks to see if it is https and if true does nothing. However if it is http it replaces http with https.

if (str.indexOf('https') === -1) {
  str = str.replace('http', 'https')
}

2
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Jun 20, 2020 at 23:33
  • This answer is related to this question. stackoverflow.com/questions/11300906/…
    – javed
    Dec 30, 2020 at 7:43
2

Functional way

window.location.protocol === 'http:' && (location.href = location.href.replace(/^http:/, 'https:'));
1
  • I like it!! Double quotes are sexier to me like a HUG! Love ur answer
    – Jade Hamel
    Oct 10, 2022 at 3:40
-2

I have just had all the script variations tested by Pui Cdm, included answers above and many others using php, htaccess, server configuration, and Javascript, the results are that the script

<script type="text/javascript">        
function showProtocall() {
        if (window.location.protocol != "https") {
            window.location = "https://" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
            window.location.reload();
        }
    }
    showProtocall();
</script> 

provided by vivek-srivastava works best and you can add further security in java script.

-2

Hi i used this solution works perfectly.No Need to check, just use https.

<script language="javascript" type="text/javascript">
document.location="https:" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
</script>
1
  • 6
    wont this refresh the page even if the protocol is https?
    – Anthony
    Dec 15, 2017 at 21:34

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.