问题描述
我正在检修其他人为我的组织建立的网站。它最初是使用不太好的锚链接设置的,其中包含空格。我将这些锚替换为新的锚,它们会更好地工作。
I'm overhauling a website that someone else built for my organization. It was originally set up with "not so great" anchor links which included spaces. I have replaced those anchors with new ones that will work better.
示例:
一个旧锚看起来像这样 / course /#To Have
哪个浏览器会幸运地转换为 / course /#To%20Have
。我将锚点更改为: / course /#to-have
。
Example:One of the old anchors looked like this /course/#To Have
which browsers would luckily convert to /course/#To%20Have
. I changed that anchor to this: /course/#to-have
.
我现在要制作确保可能已经在社交媒体上共享的锚或可以从其他网站链接的锚仍然有效;我正在计划通过.htaccess文件中的重定向来执行此操作,例如:
I'm now wanting to make sure that any anchors that may have been shared on social media or that could be linked to from other websites still work; I was planning on doing this via redirect in the .htaccess file, such as this one:
重定向301 / course /#To%20Have /课程/#要拥有
经过一些研究,我发现由于#这是不可能的
在网址中。而且我也没有看到将锚重定向到另一个锚的示例。
After some research I've found that this is not possible due to the #
in the URLs. And I also have not seen examples where an anchor was redirected to another anchor.
这可能吗?
推荐答案
如我的评论所述, .htaccess
不可能。
As mentioned in my comment, this is not possible with .htaccess
.
原因是:哈希部分(称为片段)实际上并未发送到服务器,因此Apache将无法接收它。服务器只能提取之前的所有内容,这在的语法部分中进行了描述。
Reason being: the hash part (known as the fragment) is not actually sent to the server, and so Apache would not be able to pick it up. Servers may only pick up everything before that, which is described in the Syntax section of this article.
作为替代方案,我建议您在滚动到其位置之前,使用JavaScript转换该片段。您可以通过提取 [window。] location.hash
的值来实现(方括号中的部分作为 location $ c是可选的$ c>在全局范围内也可用),如下所示:
As an alternative, I would recommend that you use JavaScript to convert the fragment before scrolling to its location. You can do that by pulling in the value of [window.]location.hash
(the part in square parenthises is optional as location
is also available in the global scope) if it exists, as shown below:
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;
}
这篇关于将旧的锚链接重定向到新的锚链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!