LoginSignup
3
4

More than 5 years have passed since last update.

Github Pages でVueのrouterが動かなくてハマった件の対応

Last updated at Posted at 2018-03-16

トップからrouter-linkを辿ったときは正常にページ遷移できるけど、
外部から直リンクでアクセスしたら404になるやんけ!
……と困ったときの対応メモです。
手間を掛けず、サクッと対応できる方法、ということで。

概要

そもそも論、実際には存在していないページにアクセスしようとしているから404が出るわけで、
まず404ページからドキュメントルートに飛ばしてから、うまく表示できるような細工をするという流れになります。

404ページの作成

404ページにて、アクセスしたパスを記録したうえでドキュメントルートに遷移させてあげます。
ルート直下に404.htmlを作ればOK。

404.html
<!doctype html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script>
    // sessionStorageにアクセスしたURLを記録しておく
    sessionStorage.redirect = location.href;
  </script>
  <!-- ドキュメントルートに遷移させる -->
  <meta http-equiv="refresh" content="0;URL='/'"></meta>
</head>
<body>
</body>
</html>

Vue側の準備

Vueの方は基本的に通常通りページ構築すればOK。
必要に応じてベースディレクトリの設定を修正しましょう。

index.htmlだけ、ちょこっと細工をします。
下記をhead内に追記。

index.html
<script>
  (function(){
    // 保存しておいたURLを取り出す
    var redirect = sessionStorage.redirect;
    delete sessionStorage.redirect;
    if (redirect && redirect != location.href) {
      // historyを書き換える。これで正常にページ遷移を行ったときの表示となる。
      history.replaceState(null, null, redirect);
    }
  })();
</script>

雑感

便利で快適なGithub Pagesをご利用ください。

参考

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4