Preserve the #some anchor

Hello,
I have a website that does use the alias to redirect people from a generic URL to the latest version of the documentation. Nevertheless when the users have the link with an anchor ex: carvel.dev/kapp-controller/docs/latest/packaging-tutorial/#creating-the-custom-resources instead of being redirected to carvel.dev/kapp-controller/docs/v0.32.0/packaging-tutorial/#creating-the-custom-resources they get redirected to carvel.dev/kapp-controller/docs/v0.32.0/packaging-tutorial/

Is there a way, with the alias, to keep keep the anchor when the user is redirected?

Redirection can be implement server-side or client-side.

Hugo’s aliases is client-side, creating an HTML page with an meta http-equiv="refresh"using this template. You could override this template by creating layouts/alias.html, and add some JS to capture and append the query string and fragment. Something like:

<!DOCTYPE html>
<html{{ with site.LanguageCode | default site.Language.Lang }} lang="{{ . }}"{{ end }}>
  <head>
    <title>{{ .Permalink }}</title>
    <link rel="canonical" href="{{ .Permalink }}">
    <meta name="robots" content="noindex">
    <meta charset="utf-8">
    <script>
      window.location = "{{ .Permalink }}" + window.location.search + window.location.hash;
    </script>
  </head>
</html>

However, whenever possible, use server-side redirection instead. The “how” of this depends your hosting setup.

1 Like

I don’t think many servers support redirecting the anchor, in the Netlify Docs for instance it sounds like the hash in sense of anchor-hash is lost. There are ways to use the hash for PWAs inside of the URL (if they are followed by at least one slash they tend to loose their “anchor” status.

Long story short: I think for this specific requirements the solution you gave might be the only one working.

We’re not talking about rewriting the query string or fragment, but instead retaining them.

With Apache 2.4:

Redirect 301 /junk-a.htm /junk-b.htm

Now visit this page and watch what happens:

https://www.mooring.com/junk-a.htm?a=b#foo

The query string and fragment are retained.

1 Like

I am impressed. This must have changed over time. I remember having to write some form of a parameter to the redirect command so it retained at least the ? parameters.

Looks good, @jmooring solution worked. thanks for the help :smiley:

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.