Christian Heilmann

Redirecting GitHub Pages

Tuesday, August 3rd, 2021 at 6:06 pm

Monopoly card redirection to jail

Today I finished moving the Edge Tools for VS Code extension documentation to its official space in the Microsoft docs. That meant I needed to redirect the documentation I hosted with GitHub pages in a docs folder/branch of the repository.

There are plugins available for that, but I didn’t want to install any extra features on the repository, so I chose a simpler approach.

You can define HTML templates for your GitHub pages in a folder called _layouts and connect them using the Markdown frontmatter. So if you create a file called test.md you can define a template called forward. You can also add a target to redirect to, in this case https://example.com

test.md:

---
layout: forward
target: https://example.com
---
... rest of your markdown ...

Your forward.html template in the _layouts folder can use a meta redirect to the target. In its most basic form this can be:

forward.html:

<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="refresh" content="0;url={{ page.target }}"/>
    <link rel="canonical" href="{{ page.target }}"/>
    <title>Redirecting</title>
</head>
<body>
    <p>Document has moved, if you aren't automatically redirected 
    <a href="{{ page.target }}">go here</a>.</p>
</body>
</html>

That means that if someone goes to the test document in your GitHub pages, they will get redirected to example.com

You can see this in action in this GitHub demo repo I quickly put together. I’ve added quite a few more options to redirect, such as definition of the time and displaying different titles and text. You can read it all and try out the demos in the README.

Share on Mastodon (needs instance)

Share on Twitter

My other work: