我的 _redirects 文件位于我的 React 应用程序的公共文件夹中,并且添加了一个重定向规则
/* /index.html 200
,效果完美。
然后我添加了另一条规则来将我的应用程序代理到我的 api 服务器
/api/* https://api.com/ 200!
它不起作用。
整个文件看起来像这样
/* /index.html 200
/api/* https://api.com/ 200!
正如我所说,全局重定向
/*
推翻了/api/*
,我无法让它工作。
注意:我尝试过像这样重新排列它们
/api/* https://api.com/ 200!
/* /index.html 200
在这种情况下,应用程序卡在“找不到页面”
注意:我尝试过像这样重新排列它们
/api/* https://api.com/ 200! /* /index.html 200
在这种情况下,应用程序卡在“找不到页面”
您被困在 404 页面,因为
https://api.com/
从您的后端将家乡路由作为 404 处理(当您在浏览器地址栏中的 url 类似于:/api/blah/blah
时)。
使用此规则
/api/* https://api.com/ 200!
,*
上的星号(/api
)用于指示/api/
之后的任何内容与https://api.com/
(家乡路线)匹配。
这是一个问题,因为您想要的是
https://api.com/
与/api/
之后的任何内容匹配,例如;/api/blog/2010
应与 https://api.com/blog/2010
匹配。/api/blog/2010
与 https://api.com/
匹配
这就是您的
_redirect
文件的样子:
/api/* https://api.com/:splat 200!
/* /index.html 200
您需要指定splat。
在 from URL(
/api/*
) 上使用星号,您还需要在 to URL(https://api.com/:splat
) 上指示 splat,它将映射到 /api/*
之后的任何内容。因此像 /api/blog/2010
这样的 URL 将被写入 https://api.com/blog/2010
Netlify 重定向引擎将处理它找到的第一个匹配规则,从上到下读取。
所以订单如下:
/* /index.html 200
/api/* https://api.com/:splat 200!
意味着第一个重定向规则(
/* /index.html 200
)将被处理,因为它始终匹配。第二个(/api/* https://api.com/:splat 200!
)不会被击中,即使浏览器地址栏像/api/blah/blah
。即使规则上有 !
,仍会遵循重定向的顺序。
更具体的规则应该在顶部定义。如图:
/api/* https://api.com/:splat 200!
/* /index.html 200