当在浏览器中的“生产"目录中直接访问url时,仅GatsbyJs客户端的路径会转到404页. [英] GatsbyJs client only paths goes to 404 page when the url is directly accessed in browser in "production"

查看:157
本文介绍了当在浏览器中的“生产"目录中直接访问url时,仅GatsbyJs客户端的路径会转到404页.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个Gatsby应用程序,并将gatsby-node.js配置为仅创建客户端路径,这些路径在开发中都可以正常工作,而直接访问路径的url却不在生产环境中.

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.

示例:

if(page.path.match(/^\/sample/)){
     page.matchPath = "/sample/:value1/:value2/:value3";
     createPage(page)
  }

我正在使用heroku来部署应用程序

I am using heroku to deploy the app

推荐答案

原因

尽管客户端路由器知道此路径,但没有相应的HTML文件.当浏览器查看站点时,它首先加载由gatsby生成的404.html文件,其中包括客户端路由器.路由器完成初始化后,便会读取路径并加载正确的页面.意味着您最终到达了正确的位置,但在错误的页面上停留了半秒钟.

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.

如何修复

一般的解决方案是告诉服务器将/sample/路径重定向到您的/sample/index.html文件.进行此操作的方式取决于您的主机,但是如果您要查找它,我将为各种主机提供该技术的名称.通常称为URL重写,每个主要的托管平台都应支持它.

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

gatsby部署文档的Heroku部分建议使用 heroku-buildpack-static 模块,该模块内置了对自定义路由"的支持它将使用以下语法为您的案例解决此问题:

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放大

您需要在AWS Amplify控制台中添加重定向.对于此示例,参数为:

You need to add the redirect in the AWS Amplify console. For this example, the params are:

  • 源URI:/sample/<*>
  • 目标URI:/sample/index.html
  • 类型:200
  • Source URI: /sample/<*>
  • Target URI: /sample/index.html
  • Type: 200

这篇关于当在浏览器中的“生产"目录中直接访问url时,仅GatsbyJs客户端的路径会转到404页.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆