GitHub pages から他サイトにリダイレクト

やりたいこと

GitHub pages でホストしていたドキュメントをRead the Docs に移行したので、GitHub pages からリダイレクトしたい。 ページ構成は同じなのでサブページもリダイレクトしてほしい:

手順

  • まずgh-pages branch のファイルを消す
git checkout gh-pages
git rm -r *
  • index.html を作って、index page をリダイレクトさせる
<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>Redirecting to https://hsnf.readthedocs.io/en/latest/</title>
    <meta http-equiv="refresh" content="0; URL=https://hsnf.readthedocs.io/en/latest/">
    <link rel="canonical" href="https://hsnf.readthedocs.io/en/latest/">
</head>
</html>
  • 404.html でサブページもリダイレクトさせる
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>404</title>
    <script>
        window.onload = function () {
            if (window.location.href.includes("lan496.github.io/hsnf")) {
                const redirectLocation = window.location.href.replace(
                    "lan496.github.io/hsnf",
                    "hsnf.readthedocs.io/en/latest"
                );
                document.getElementById("body").innerHTML = "Redirecting to " + redirectLocation + " ...";
                window.location.href = redirectLocation;
            }
        }
    </script>
</head>
<body id="body" style="text-align: center">
    Page not found
</body>
</html>
  • push する
git add index.html
git add 404.html
git commit
git push origin gh-pages

これでリダイレクトできる

References