LoginSignup
22
12

More than 3 years have passed since last update.

Firebase HostingでSPAのリロード時にPage Not Foundになる時の対策

Last updated at Posted at 2019-07-20

Firebase Hostingにcreated-react-appで作成したSPAをホストしたところ、リロード時にPage Not Foundになってしまったので対策をまとめます。

追記

$ firebase init時に画像のようにSPAのURLの挙動を設定できる設問があるようです。
「Configure as a single-page app...」 の部分です。
スクリーンショット 2019-07-22 1.23.10.png
これをy + Enterfirebase.jsonルールを追加してくれるようです。

Firebase Hosting のデフォルトの挙動

Firebase Hosting はデフォルトでは静的なindex.htmlファイルを読みに行くようです。Reactではreact-routerなどのルーティングライブラリを利用するので実際にはindex.htmlはありません。なのでルートディレクトリ以外でリロードをするとこのように404を返してきます。

スクリーンショット 2019-07-20 19.03.33.png

対策

firebase.jsonファイルのhosthingプロパティにrewritesルールを追加して、公開ディレクトリ配下のアクセスを全てルートのindex.htmlを読みに行くようにします。

Before

firebase.json
{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "hosting": {
    "public": "build",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
  }
}

After

firebase.json
{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "hosting": {
    "public": "build",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "/public/**",
        "destination": "/public.html"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

これで404になることはなくなました。

参考

Page not found when reloading Angular page on Firebase

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