问题
I have created a Gatsby app and configured gatsby-node.js
to a create client only paths, which are all working fine in development while directly accessing the url of the path but not in production.
example :
if(page.path.match(/^\/sample/)){
page.matchPath = "/sample/:value1/:value2/:value3";
createPage(page)
}
I am using heroku
to deploy the app
回答1:
The Why
While the client-side router knows about this path, there is no corresponding HTML file. When the browser looks at the site it first loads the 404.html
file generated by gatsby, which includes the client-side router. Once the router completes its initialization it reads the path and loads the correct page. Meaning you end up at the right place but there's half a second of landing on the wrong page.
How to fix It
The general solution is to tell your server to redirect the /sample/
path to your /sample/index.html
file. The way to do this depends on your host, but I'll provide the name of the technique for various hosts in case you want to look it up. It's usually called URL Rewriting and should be supported by every major hosting platform.
- Netlify: Redirects
- Firebase: URL Rewrites
- Nginx: Rewrite Directions
- Apache: Mod_Rewrite
- Amazon S3: Configuring a Webpage Redirect
- Amazon Amplify: Using redirects
- Cloudflare: URL Forwarding
Heroku
The Heroku section of the gatsby deploy documentation suggests using the heroku-buildpack-static module which has built-in support for "custom routes" which will solve this for your case using syntax like this:
{
"routes": {
"/sample/**": "sample/index.html",
}
}
AWS Amplify
You need to add the redirect in the AWS Amplify console. For this example, the params are:
- Source URI:
/sample/<*>
- Target URI:
/sample/index.html
- Type: 200
来源:https://stackoverflow.com/questions/52051090/gatsbyjs-client-only-paths-goes-to-404-page-when-the-url-is-directly-accessed-in