DEV Community

loading...
Cover image for Redirecting GitHub Pages

Redirecting GitHub Pages

Christian Heilmann
Open Web guy at Microsoft and long-time JavaScript user
Originally published at christianheilmann.com ・2 min read

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 ... 
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (3)

Collapse
nfrankel profile image
Nicolas Frankel

Don't reinvent the wheel: check the JekyllRedirectFrom plugin. It does exactly the same... and more.

Collapse
codepo8 profile image
Christian Heilmann Author

uhm:

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.

Collapse
devoresyah profile image
DeVoresyah ArEst

thanks for sharing, I just moved from github pages into netlify for my framework documentation, will try this asap