Motomichi Works Blog

モトミチワークスブログです。その日学習したことについて書いている日記みたいなものです。

create-react-appしてbuildしたアプリケーションをnetlifyにデプロイしてリロードしたとき404になるのを解決する

参考にさせていただいたページ

解決したい事象

以下の手順を実行したときにnetlifyが用意している404ページが表示されてしまいました。

  1. yarn create react-app my-app --template typescript でreactアプリケーションをcreateします。
  2. /exampleページを作ります。
  3. react-router-domのLinkコンポーネントで、rootページから/exampleページへのリンクを設置します。
  4. yarn build します。
  5. buildされたディレクトリ/buildをnetlifyにデプロイします。
  6. https://xxxxx.netlify.app(rootページ)」にアクセスします。
  7. リンクをクリックして「 https://xxxxx.netlify.app/example」に遷移します。
  8. リロードするとnetlifyが用意している404ページが表示されてしまいます。

以下のようなページが表示されました。 f:id:motomichi_works:20211228191126p:plain

Page Not Found
Looks like you've followed a broken link or entered a URL that doesn't exist on this site.

Back to our site

If this is your site, and you weren't expecting a 404 for this path, please visit Netlify's "page not found" support guide for troubleshooting tips.

どうしたいか

rootページ以外でリロードしたとき、サーバーにリクエストして同期的に遷移したときも、reactアプリケーションのルーティングに従ってページを表示したい。

解決方法

  1. 参考ページにならって、build/_redirectsファイルを作成し、以下の通り記述します。
    /* /index.html 200
  2. デプロイし直します。