LoginSignup
12
11

More than 5 years have passed since last update.

Nuxt.jsをspa modeでGitHub Pagesで使う時に404にならないようにする

Posted at

サーバを無料で使いたいマンなので全てGitHub Pagesでなんとかしようとするマンです。よろしくお願いします。

GitHub PagesでSPAしようとすると、index.html以外にアクセスされた場合にGitHub Pagesで用意された404が表示されてしまうのでなんとかしようとした時の記録です。

SPAモードにする

nuxt.config.js
module.exports = {
  mode: 'spa' // これを追記
}

index.html以外にアクセスされた際にNuxt.js(index.html)にリダイレクト

static/404.html
<script>
  sessionStorage.redirect = location.href;
</script>
<meta http-equiv="refresh" content="0;URL='/'"/>
static/js/404-redirect-ghpages.js
;(function() {
  const redirect = sessionStorage.redirect
  delete sessionStorage.redirect
  if (redirect && redirect !== location.href) {
    history.replaceState(null, null, redirect)
  }
})()
nuxt.config.js
module.exports = {
  head: {
    script: [{ src: '/js/404-redirect-ghpages.js' }] // これを追記
  },
}

デプロイ

$ yarn add --dev push-dir
package.json
"scripts": {
  "build": "nuxt build",
  "deploy": "push-dir --dir=dist --branch=gh-pages --cleanup"
}
$ yarn build
$ yarn deploy

参考
https://dev.to/_evansalter/github-pages-and-single-page-apps

12
11
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
12
11