Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

reactjs - Catch all redirect for create-react-app in netlify

I have a built using create-react-app and hosted in netlify.

In this link it is mentioned that I need to write redirect rules for SPAs.

/*    /index.html   200

But redirecting to index.html is not working since no view is rendered with that URL. I also tried redirecting to / like

[[redirects]]
  from = "/*"
  to = "/"

but this is also not working.

How do I do a catch-all redirect for create-react-app?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To catch all the redirects use /* /index.html 200 in _redirects file.

According to the netlify docs, the _redirects file should be in your root build directory.

create-react-app by default creates all build files under the folder named build

so just modify the build scripts in package.json to add the _redirects in the build folder after building the app.

example.

"scripts": {
  ....
  "build": "react-scripts build && echo '/* /index.html  200' | cat >build/_redirects ",
  ...
}

If you have multiple redirects to make things easier you can create a _redirects file with all the redirects in your root(/) folder of the CRA

then in the package.json will become

"scripts": {
  ....
  "build": "react-scripts build && cp _redirects build/_redirects",
  ...
}

make sure that the build command in your netlify is yarn run build or npm run build

after making the changes in package.json simply rebuild your code.


UPDATED: much better way

IN CRA(Create React App), the build script copies every file in public directory to the build folder so just put the _redirects with the rules in the public directory without changing anything and you are good to go.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...