Html 自动重定向到https?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4954768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:38:32  来源:igfitidea点击:

automatic redirection to https?

html

提问by LanceBaynes

if i use:

如果我使用:

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

<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.

在 html 代码中,它将无休止地循环并刷新 https 页面。

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

如何将用户重定向到 https?[关于一个index.html文件]

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

如果他们只使用“http”,我需要在“index.html”的html代码中放入什么来重定向它们?

Thanks

谢谢

回答by Brad Christie

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.

也许?只要你不介意小的 javascript 依赖。

回答by Alexander Zaldostanov

Hope this helps

希望这可以帮助

<html>
<head>
<title>
Redirecting...</title></head>
<script language="JavaScript">
function redirectHttpToHttps()
{
    var httpURL= window.location.hostname + window.location.pathname + window.location.search;
    var httpsURL= "https://" + httpURL;
    window.location = httpsURL;
}
redirectHttpToHttps();
</script>
<body>
</body>
</html>

回答by Amon Bazongo

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.

在网络层面,可以使用像 Traefik 这样的边缘路由器。在应用层,可以使用反向代理进行重定向。反向代理(如 Ngnix)或服务(如 Cloudflare 或 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.

另请注意,如果您在 Firebase Hosting 等平台上托管您的网站,默认情况下您将自动重定向到 https。