简体   繁体   English

基于域名的JavaScript重定向

[英]JavaScript redirect based on domain name

I am not looking for a simple redirect. 我不是在寻找简单的重定向。

What I am trying to do is this. 我想做的就是这个。

Person A loads site BOB.com and clicks a link to page X. 人物A加载网站BOB.com,然后单击指向页面X的链接。
Person B loads site TIM.com and clicks a link to the same page X. 人物B加载站点TIM.com,然后单击指向同一页面X的链接。

Page X has a javascript command on it that says, If user came from site Bob.com then redirect to Bob.com/hello. X页面上有一个javascript命令,上面写着:如果用户来自站点Bob.com,则重定向到Bob.com/hello。
If user came from TIM.com then redirect to Tim.com/hello. 如果用户来自TIM.com,则重定向到Tim.com/hello。
If user didnt come from ether then redirect to Frank.com/opps. 如果用户不是来自以太坊,则重定向到Frank.com/opps。

This page X is going to handle 404 errors for multiple domains so it will need to ONLY look at the domain name upto ".com". 该页面X将处理多个域的404错误,因此仅需查看域名最多为“ .com”的域名即可。 It should ignore everything past the ".com". 它应该忽略“ .com”之后的所有内容。

This is the script I started with. 这是我开始使用的脚本。

<script type='text/javascript'>
var d = new String(window.location.host);
var p = new String(window.location.pathname);
var u = "http://" + d + p;
if ((u.indexOf("bob.com") == -1) && (u.indexOf("tim.com") == -1))
{
u = u.replace(location.host,"bob.com/hello");
window.location = u;
}
</script> 

Use document.referrer 使用document.referrer

if(/http:\/\/(www\.)?bob\.com/.test(document.referrer)) {
   window.location = "http://bob.com/hello";
}

else if(/http:\/\/(www\.)?tim\.com/.test(document.referrer)) {
   window.location = "http://tim.com/hello";
}

else {
   window.location = "http://frank.com/oops";
}

Instead of the regex, you can use indexOf like you did initially, but that would also match thisisthewrongbob.com and thisisthewrongtim.com ; 您可以像最初一样使用indexOf代替正则表达式,但这也可以匹配thisisthewrongbob.comthisisthewrongtim.com the regex is more robust. 正则表达式更强大。

document.referrer是要去的地方

Use document.referrer to find where the user came from. 使用document.referrer查找用户来自何处。

The updated code is 更新的代码是

<script type='text/javascript'>
  var ref = document.referrer,
      host = ref.split('/')[2],
      regexp = /(www\.)?(bob|tim).com$/,
      match = host.match(regexp);

  if(ref && !regexp.test(location.host)) { 
  /* Redirect only if the user landed on this page clicking on a link and 
    if the user is not visiting from bob.com/tim.com */
    if (match) {
      ref = ref.replace("http://" + match.shift() +"/hello");
    } else {
      ref = 'http://frank.com/oops';
    }

    window.location = ref;
  }
</script>

working example (it displays a message rather than redirecting) 工作示例 (显示消息而不是重定向)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM