将旧锚链接重定向到新锚链接

Redirecting old anchor links to new anchor links

我正在检修其他人为我的组织构建的网站。它最初是用包含空格的 "not so great" 锚链接设置的。我已经用效果更好的新锚替换了那些锚。

示例: 一个旧的锚点看起来像这样 /course/#To Have,浏览器会幸运地转换为 /course/#To%20Have。我将该锚点更改为:/course/#to-have.

我现在想确保任何可能已在社交媒体上共享或可能从其他网站链接到的锚点仍然有效;我正计划通过 .htaccess 文件中的重定向来执行此操作,例如这个:

Redirect 301 /course/#To%20Have /course/#to-have

经过一些研究,我发现由于 URL 中的 #,这是不可能的。而且我也没有看到一个锚点被重定向到另一个锚点的例子。

这可能吗?

如我的评论所述,.htaccess 无法做到这一点。

原因是:散列部分(称为 片段 )实际上并未发送到服务器,因此 Apache 无法获取它。服务器可能只会获取之前的所有内容,这在 this article.

的语法部分中有描述

作为替代方案,我建议您在滚动到其位置之前使用 JavaScript 转换片段。您可以通过拉入 [window.]location.hash 的值(方括号中的部分是可选的,因为 location 在全局范围内也可用)来实现,如下所示:

if (window.location.hash) {

    // Function to 'slugify' the fragment
    // @see https://gist.github.com/mathewbyrne/1280286#gistcomment-1606270

    var slugify = function(input) {
        return input.toString().toLowerCase().trim()
            .replace(/\s+/g, '-')           // Replace spaces with -
            .replace(/&/g, '-and-')         // Replace & with 'and'
            .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
            .replace(/\-\-+/g, '-');        // Replace multiple - with single -
    }

    // Now get the hash and 'slugify' it

    var hash = slugify(window.location.hash.split('#')[1]);

    // Go to the new hash by setting it

    window.location.hash = '#' + hash;

}