20
$\begingroup$

if i use:

<meta http-equiv="REFRESH" content="0;url=https://www.the-domain-you-want-to-redirect-to.com/index.html">

in the html code then it will endlessly loop and refresh the https page.

How can i redirect the users to https? [regarding one index.html file]

What do i need to put in the html code of that "index.html" to redirect them, if they use only "http"?

Thanks

$\endgroup$
1
  • $\begingroup$ What kind of webserver is used? Is it IIS or Apache? And what technology do you use? PHP, .NET? $\endgroup$ Commented Feb 10, 2011 at 8:20

2 Answers 2

51
$\begingroup$
var loc = window.location.href+'';
if (loc.indexOf('http://')==0){
    window.location.href = loc.replace('http://','https://');
}

maybe? as long as you don't mind a small javascript dependency.

$\endgroup$
Sign up to request clarification or add additional context in comments.

9 Comments

I think too much code instead of scripts. +1 Elegant solution.
@Mark It was basically the same. Plus, @Brad's answer actually works. Mine don't. It turned out, window.location.protocol doesn't take getting a value assigned to too kindly.
@Linus: Ah..well then. I just don't like that this solution searches the whole string...twice. Not that efficiency really matters.
i created this .html file: pastebin.com/raw.php?i=vVtktSjM and when i load it in http, it doesn't get's redirected to https, javascript is enabled, what am i doing wrong?
@john just confirm it's a string and not undefined.
|
2
$\begingroup$

This could be more elegant

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

However, this is an answer in a code level. To answer the question a bit more broadly, it is even possible to not even touch the code for that, like in the network level or in the application level.

In the network level, you can use an edge router like Traefik. In the application level, you can use a reverse proxy for the redirection. Reverse proxies like Ngnix or services like Cloudflare or AWS Cloudfront.

Also note that in case you host your website on platforms like Firebase Hosting, you will have the automatic redirection to https by default.

$\endgroup$

1 Comment

that will be redirecting for http and https you should be doing something like if (/http:/.test(window.location.href)) {

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.