GatsbyJs client only paths goes to 404 page when the url is directly accessed in browser in “production”

前端 未结 4 1734
谎友^
谎友^ 2020-12-28 15:44

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

4条回答
  •  悲哀的现实
    2020-12-28 16:38

    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.htmlfile. 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

提交回复
热议问题