Javascript 检查网页url,如果输入为http,则生成https

Javascript 检查网页url,如果输入为http,则生成https,javascript,html,Javascript,Html,我有一个使用https路由的网页,所有这些都运行良好。 我注意到我可以将其更改为http,页面仍然加载 我正在尝试检查窗口url,并使其成为https,如果它是作为http输入的。仅适用于此页面并使用Jquery或Javascript。(我知道大多数人会建议不要使用脚本进行安全保护) 这对我不起作用: <script> var url = window.location.pathname; if url.match('^http://') { url = url.replace(/^

我有一个使用https路由的网页,所有这些都运行良好。 我注意到我可以将其更改为http,页面仍然加载

我正在尝试检查窗口url,并使其成为https,如果它是作为http输入的。仅适用于此页面并使用Jquery或Javascript。(我知道大多数人会建议不要使用脚本进行安全保护)

这对我不起作用:

<script>
var url = window.location.pathname;
if url.match('^http://')
{
url = url.replace(/^http:\/\//, 'https://');
    window.location.pathname = url;
}

var url=window.location.pathname;
如果url.match(“^http://”)
{
url=url。替换(/^http:\/\/,'https://');
window.location.pathname=url;
}


如果您真的想在客户端执行此操作,请向

表示感谢:

<script>

   if (  window.location.protocol != 'https:' ) {
           window.location = document.URL.replace("http://","https://");
    }

</script>

如果(window.location.protocol!=“https:”){
window.location=document.URL.replace(“http://”、“https://”);
}

您应该在服务器端执行此操作。这可能对您不起作用,因为您缺少
if
条件的括号。我很确定这至少是其中的一部分。但是,是的,在服务器端执行。应该使用.htaccess完成。请参见
window.location.pathname
返回URL中
.tld
后面的路径。您想使用
window.location.protcol
。但即使如此,这种类型的操作最好在.htaccess中完成。CSRF或XSS是否能够将其作为脚本并使其工作?您应该锚定表达式,以免它取代URL中的任何位置,即
/^http:\/\/
。或者像这样使用子字符串