0

我正在创建一个自定义会员计划。我希望我的链接尽可能对 SEO 友好,因此我将使用附加到 URL 的 Javascript 哈希来发送会员 ID、读取会员 ID、存储点击,然后 301 重定向到他们链接的页面也。这样我们就没有任何规范问题,并且每个附属链接都通过链接汁!

现在,我将如何阅读以下 URL?

www.mydomain.com/seo-friendly-url#ref=john

在获取 ref 的哈希值并添加点击后,我将如何 301 将用户重定向回

www.mydomain.com/seo-friendly-url

任何帮助是极大的赞赏!

4

2 回答 2

3

片段标识符(# 之后的部分)不会发送到服务器,因此任何可能发出 HTTP 响应(301 重定向需要它)的东西都无法读取它们。

于 2011-09-23T21:39:00.853 回答
0

URL 的“散列”部分不会传递给服务器,因此您将无法直接利用此数据进行任何服务器端重定向或处理。但是,可以在页面加载时获取哈希并通过 AJAX 或重定向将其传递给服务器:

立即将用户重定向www.mydomain.com/seo-friendly-url#ref=johnwww.mydomain.com/seo-friendly-url/ref/john

if (window.location.hash.match(/#ref=/))
    window.location = window.location.href.replace('#ref=', '/ref/')

...但是,为什么不习惯www.mydomain.com/seo-friendly-url/ref/john开始并节省额外的腿部工作呢?另一条路径,通过 AJAX,涉及在页面加载后读取哈希值并将其发送到服务器进行记录。

(注意:此代码使用通用的跨浏览器 XMLHTTPRequest来发送 AJAX GET 请求。替换为您的库的实现 [如果您使用的是库])

window.onload = function () {
    // grab the hash (if any)
    var affiliate_id = window.location.hash;
    // make sure there is a hash, and that it starts with "#ref="
    if (affiliate_id.length > 0 && affiliate_id.match(/#ref=/)) {
        // clear the hash (it is not relevant to the user)
        window.location.hash = '';
        // initialize an XMLRequest, send the data to affiliate.php
        var oXMLHttpRequest = new XMLHttpRequest; 
        oXMLHttpRequest.open("GET", "record_affiliate.php?affiliate="+affiliate_id, true);
        oXMLHttpRequest.onreadystatechange = function() { 
            if (this.readyState == XMLHttpRequest.DONE) { 
                // do anything else that needs to be done after recording affiliate
            } 
        }
        oXMLHttpRequest.send(null);
    }
}
于 2011-09-23T22:07:56.060 回答