【问题标题】:Catch all redirect for create-react-app in netlify在 netlify 中捕获 create-react-app 的所有重定向
【发布时间】:2019-05-05 09:17:56
【问题描述】:

我使用create-react-app 构建并托管在netlify

在这个link 中提到我需要为 SPA 编写重定向规则。

/*    /index.html   200

但是重定向到index.html 不起作用,因为没有使用该 URL 呈现视图。 我也尝试重定向到/ 喜欢

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

但这也行不通。

如何为create-react-app 进行全面重定向?

【问题讨论】:

    标签: reactjs create-react-app netlify


    【解决方案1】:

    要捕获所有重定向,请在 _redirects 文件中使用 /* /index.html 200

    根据 netlify 文档,_redirects 文件应该在您的构建根目录中。

    create-react-app 默认在build文件夹下创建所有构建文件

    所以只需在构建应用程序后修改package.json 中的build scripts 以在构建文件夹中添加_redirects

    例子。

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

    如果您有多个重定向以简化操作,您可以在 CRA 的根 (/) 文件夹中创建一个包含所有重定向的 _redirects 文件

    那么在package.json就会变成

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

    确保您的 netlify 中的构建命令是 yarn run buildnpm run build

    package.json 中进行更改后,只需重新构建您的代码。


    更新:更好的方法

    在 CRA(创建 React 应用程序)中,构建脚本将公共目录中的每个文件复制到构建文件夹中,因此只需将 _redirects 与规则一起放在公共目录中,无需更改任何内容,你很好去。

    【讨论】:

    • 我还需要在里面有_redirects/* /index.html 200 吗?
    • _redirects/* /index.html 200 所在的文件名
    • 详情请查看create-react-appdocs中的“支持客户端路由”。
    • 您实际上可以在/public 文件夹中创建一个具有单行的_redirects 文件。 build 命令将文件复制到/build 目录。无需即时显式创建或复制文件。这样,您也可以将其签入到您的 Git 中(或者如果您不想要它,请添加到 .gitignore
    【解决方案2】:

    有两 (2) 种方法可以创建 redirects when hosting on Netlify

    • publish 目录根目录下的_redirects 文件(CRA 中的/build
    • [[redirects]] 列表位于存储库(项目)根目录下的 netlify.toml 配置文件中

    /public/_redirects(选项 1)

    _redirects放到/public目录下。 CRA 在运行构建命令时会将/public 中的所有文件复制到构建目录中。

    /public/_redirects

    /* /index.html  200
    

    /netlify.toml(选项 2)

    netlify.toml 放在要部署到 Netlify 的项目(存储库)的根 (/) 目录中。如果netlify.toml 已经存在,您可以将重定向行添加到它的末尾。

    /netlify.toml

    [[redirects]]
      from = "/*"
      to = "/index.html"
      status = 200
      force = false
    

    注意:这些选项可以组合,但请记住_redirects 将覆盖netlify.toml 中具有相同源(发件人)路径的条目。

    您还可以使用redirects playground 从一种格式转换为另一种格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      相关资源
      最近更新 更多