Renaming an anchor without breaking external links

On a quality website, external links keep working even many years later even if original URLs changed. A URL may change for multiple reasons, for example:

  • changing the URL scheme of the entire site;
  • changing a part of a human-friendly URL to a better one for a single page;
  • moving a page to a different section of the site.

For a webpage or a file, this can be solved with an external redirection from the original URL to the new one with the server’s HTTP response header Location in conjunction with the HTTP status 301 Moved Permanently.

But what if the URL changed as a result of renaming an anchor (hash)? Anchors are based on using identifiers (id attributes) of elements. For example, going to the #h-foo link will automatically scroll the page to the element with the h-foo identifier if the page contains such an element.

The id attribute can only contain a single identifier. So when changing the identifier, old links can be kept working by creating an empty semantically neutral element SPAN with the old identifier and inserting it into the beginning of the original element:

Before:
<h2 id="h-foo">Example</h2>
After:
<h2 id="h-bar"><span id="h-foo"></span>Example</h2>

Thanks to this, links to the old anchor — #h-foo — will remain working.