2

I'm attempting to redirect all external links thru a php file with the url of the external site set as a variable.

Example. If my site (mysite.com) has a link to google.com/results/1234 I'd like to automatically rewrite the url to something linke mysite.com/external.php?p=google.com/results/1234.

I'd like an htaccess solution, as I am unable to change files associated with external urls without affecting other urls on the site.

I DO Not want to redirect any link with mysite.com.

If someone could point me in the right direction, I would really appreciate it.

4

1 回答 1

1

通过 .htacess 文件不可行。.htaccess 只能用解析到您的 Web 服务器的域名重写传入的 URL。它无法控制传出 URL,因为这些请求直接发送到传出 Web 服务器(在您的示例中为 google.com)。

onclick您可能需要的是一个脚本解决方案,它通过连接到所有链接的事件来根据您的需要重定向用户。

编辑:这是使用 jQuery 的快速概念证明。这应该让你开始。

<html>
<head>
 <title>jQuery global redirector</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
 <a href="http://google.com/search?q=jquery">google url would redirect</a><br />
 <a href="http://mysite.com/somepage.php">mysite.com url won't redirect</a>
 <script>
 <!--
    $("a").click(function(e) {
      var url = e.target.href;
      if(!(url.startsWith("http://mysite.com") || url.startsWith("mysite.com"))) {
        window.location.href = "http://mysite.com/redirect.php?site=" + url;
        e.preventDefault();
      }
    });
 //-->
 </script>
</body>
</html>

您可能应该将脚本放在另一个文件中(比如redirect.js),然后有选择地将此脚本(靠近<html> 的末尾)包含在需要此类重定向的页面中。并且不要忘记导入 jQuery!

于 2013-04-26T02:56:11.117 回答