LoginSignup
0

More than 3 years have passed since last update.

GitHub Pages上のVue.jsアプリでリロードすると404になる場合の対応

Posted at

はじめに

Vue.jsで作成したSPAのWebアプリをGitHub Pagesで公開した際に、ページ上でリロードをすると404エラーとなってしまいます。
例えば、SampleというリポジトリでGitHub Pagesに公開していれば、https://〇〇.github.io/Sample/というサイトがトップページになります。
このページ上でリロードしてもエラーとはなりませんが、https://〇〇.github.io/Sample/hogeというページに遷移後、そのページ上でリロードすると、404エラーとなります。

404.htmlの作成

その対策法の1つとして、404エラーの際に表示される404.htmlを作成する方法があります。
GitHub Pagesで公開しているディレクトリ(例えばdocs)直下に404.htmlというファイルを置いておくと、404エラーとなった際に、そのページを表示します。
その404.htmlに以下のような内容を記述します。

404.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <script>
        window.location.pathname = "/Sample/"; // この部分があれば大丈夫です
    </script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>NotFound</title>
</head>
<body>
</body>
</html>

scriptにwindow.location.pathname = "/(トップページ名)/";と記述することで、404.html表示時に自動的にトップページに遷移させています。

おわりに

今回はトップページに遷移させましたが、遷移先のURLにパラメータ等をセットして、index.htmlでそのパラメータを元に再度遷移させるなどすれば、擬似的に指定したURLのページに飛ぶことができると思います。
以下の方の記事が参考になると思います。
Github pagesでハッシュなしSPAを作る[Vue.js + vue-router] - Qiita

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
0