基于域名的JavaScript重定向

时间:2011-02-07 19:23:57

标签: javascript redirect dns

我不是在寻找简单的重定向。

我想做的就是这个。

人员A加载站点BOB.com并单击指向页面X的链接 人员B加载站点TIM.com并单击指向同一页面X的链接。

页面X上有一个javascript命令,如果用户来自站点Bob.com,则重定向到Bob.com/hello。 如果用户来自TIM.com,则重定向到Tim.com/hello 如果用户没有来自以太,那么重定向到Frank.com/opps。

此页面X将处理多个域的404错误,因此它只需要查看域名“.com”。它应该忽略“.com”之后的所有内容。

这是我开始使用的脚本。

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

3 个答案:

答案 0 :(得分:6)

使用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";
}

您可以像最初一样使用indexOf而不是正则表达式,但这也会匹配thisisthewrongbob.comthisisthewrongtim.com;正则表达式更强大。

答案 1 :(得分:1)

document.referrer

的地方

答案 2 :(得分:0)

使用document.referrer查找用户来自哪里。

更新的代码是

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

正在工作example (它会显示消息而不是重定向)

相关问题