基于URL的重定向-JavaScript

Redirection based on URL - JavaScript

本文关键字:-JavaScript 重定向 URL 基于      更新时间:2023-09-26

如果有人键入"www.morgancc.edu",我希望它重定向到我们位于"www.morgencc.edu/m"的移动网站。但是,我只需要使用这个确切的URL进行重定向。如果你转到"www.morgancc.edu/proprograms"之类的网站,我不希望它重定向,这就是它目前正在做的事情。这是我迄今为止的代码:

<script type="text/javascript">
if (window.location = "www.morgancc.edu") {
   window.location.href = 'http://www.morgancc.edu/m/'; 
}
</script>

location.hostname和一个空路径似乎就是您想要的

if (window.location.hostname == "www.morgancc.edu" && 
    window.location.pathname=="" ) {
   window.location.href = 'http://www.morgancc.edu/m/'; 
}

或者查看href

if (window.location.href== "http://www.morgancc.edu") {
   window.location.href = 'http://www.morgancc.edu/m/'; 
}

您可能需要添加一些/此处或那里的

相等运算符是==,而不是=

我建议使用服务器端脚本语言来重定向访问您网站的设备。如果您的if语句中也有拼写错误,则应该使用=而不是=

<script type="text/javascript">
if (window.location == "www.morgancc.edu") {
   window.location.href = 'http://www.morgancc.edu/m/'; 
}
</script>