【问题标题】:How to make 301 redirect in Gatsby website hosted on Vercel?如何在 Vercel 上托管的 Gatsby 网站中进行 301 重定向?
【发布时间】:2021-11-04 23:35:15
【问题描述】:

image of vercel.json for reference

我在我的网站上使用 gatsby js 并将其托管在 vercel 上,现在我想为我的网站做 301 重定向,但我不想为此使用 gatsby-cloud。他们有什么办法我可以用vercel做到这一点吗?

这是https://vercel.com/docs/cli#project/redirects 的文档,但我无法正确理解它,因为它说要创建一个 vercel.json 文件,谁能帮我更好地理解它?

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: redirect gatsby vercel


【解决方案1】:

当然,你不需要 Gatsby Cloud 做重定向,你只需要服务器规则。

在 Vercel 的情况下,根据这个GitHub thread(并拉出许多类似的线程),Next 默认不支持开箱即用的 Gatsby 重定向,因此唯一可靠的方法是使用createRedirect API。在您的 createPages 函数(如果存在)中添加以下内容:

// Generally you create redirects while creating pages.
exports.createPages = ({ graphql, actions }) => {
  const { createRedirect } = actions
  createRedirect({ fromPath: '/old-url', toPath: '/new-url', isPermanent: true })
  createRedirect({ fromPath: '/url', toPath: '/zn-CH/url', Language: 'zn' })
  createRedirect({ fromPath: '/not_so-pretty_url', toPath: '/pretty/url', statusCode: 200 })
  // Create pages here
}

Next 将使用通过此操作创建的重定向并创建适当的“现在”路由。

【讨论】:

  • 我的网站托管在 vercel 上,所以这个解决方案对我有用吗?旧网址也来自我以前的网站,现在如果有人访问该旧网址,我想将用户带到新网站的网址。因此,我将所有旧 url 保存在 json 文件中,以便我可以将其映射到 fromPath 和 toPath。所以我有点好奇 CreateRedirect API 会解决我的问题吗? @ferran
  • 应该只要是Vercel自己提出的解决方案。尝试并提供反馈。
  • 好的,让我试试这个,然后给你反馈
  • 尝试此方法后我面临的问题是,实际上我必须重定向到另一个域,这是我的基本 url 不同,例如我输入 fromPath: "sunlightensaunas.co.uk/saunas"** , * * toPath: "sunlighten.com/gb-en/saunas"** . Gatsby 重定向只在内部工作,所以我认为它在这里不起作用,因为它是关于重定向到另一个域。为了使这个重定向工作,我尝试了这个插件:github.com/universse/gatsby-plugin-zeit-now 但仍然没有运气
  • 在这种情况下,这种导航应该由服务器本身处理,在这种情况下是 Vercel,但是在前端 (Gatsby) 中您无能为力,因为您需要执行该操作到达前端代码之前的重定向
猜你喜欢
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 2018-08-15
  • 2013-12-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 2017-02-04
相关资源
最近更新 更多