LoginSignup
9
8

More than 5 years have passed since last update.

Firebase Hostingのリライトルール

Last updated at Posted at 2017-11-27

Firebaseを使うと、認証やDB、WEBホスティングの機能が提供されていて、vue.jsなどを動かして、簡単にServerlessなWEBサイトを作ることができます。
angular.jsやvue.jsなどでは/index.htmlを起点にしてアプリをロードし、以降はHTML5pushstateを用いて、URLパスを書き換え、コンテンツを切り替えていきます。

リライトルール設定

以下のようにfirebase.jsonにリライトルールを設定し、全マッチしたときに、/index.htmlに渡すようにする必要があります。

firebase.json
...
  "hosting": {
  ...
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
...

リライト設定を忘れるとどうなるか

設定しなくても、一見動作します。
https://***.firebaseapp.com
にアクセスすると、トップ画面に飛んできて、/index.htmlがロードされるため、以降の動作は正常に動きます。

ところが
https://***.firebaseapp.com/blogs
のように直接パスを指定されると、404エラーページへ遷移します。

参考

公式ドキュメント/Hosting 動作をカスタマイズする
https://firebase.google.com/docs/hosting/url-redirects-rewrites

追記: firebase-cliでリライト設定

firebase-CLIを使って初期化すると、デフォルトで上記の設定ができます。

$ firebase init                                                                                       

     🔥🔥🔥🔥🔥🔥🔥🔥 🔥🔥🔥🔥 🔥🔥🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥🔥🔥 🔥🔥🔥🔥🔥🔥🔥🔥     🔥🔥🔥     🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥🔥🔥
     🔥🔥        🔥🔥  🔥🔥     🔥🔥 🔥🔥       🔥🔥     🔥🔥  🔥🔥   🔥🔥  🔥🔥       🔥🔥
     🔥🔥🔥🔥🔥🔥    🔥🔥  🔥🔥🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥   🔥🔥🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥
     🔥🔥        🔥🔥  🔥🔥    🔥🔥  🔥🔥       🔥🔥     🔥🔥 🔥🔥     🔥🔥       🔥🔥 🔥🔥
     🔥🔥       🔥🔥🔥🔥 🔥🔥     🔥🔥 🔥🔥🔥🔥🔥🔥🔥🔥 🔥🔥🔥🔥🔥🔥🔥🔥  🔥🔥     🔥🔥  🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥🔥🔥

You're about to initialize a Firebase project in this directory:

  /Users/******

Before we get started, keep in mind:

  * You are initializing in an existing Firebase project directory

? Which Firebase CLI features do you want to setup for this folder? Press Space to select features, then Enter to confirm yo
ur choices.
 ◯ Database: Deploy Firebase Realtime Database Rules
 ◯ Firestore: Deploy rules and create indexes for Firestore
 ◯ Functions: Configure and deploy Cloud Functions
❯◯ Hosting: Configure and deploy Firebase Hosting sites
 ◯ Storage: Deploy Cloud Storage security rules

ここでHostingを選択後、のちほど表示される以下の質問にYesと答えると

? Configure as a single-page app (rewrite all urls to /index.html)? Yes
✔  Wrote public/404.html
✔  Wrote public/index.html

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...

✔  Firebase initialization complete!

以下のようにfirebase.jsonが設定されます。

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

ご指摘いただき感謝

9
8
2

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
9
8