与盖茨比的动态重定向

发布于 2025-01-23 09:15:25 字数 610 浏览 2 评论 0 原文

给定一个在构建上具有动态生成的产品URL的盖茨比应用程序:

  • /x/x
  • /x/
  • product/x/variant1//x/x/x/variant2//
  • y/y/y/
  • y/y/y/variant1/
  • ...

是否有办法自动导致对每种产品的不存在的子净值访问以重定向到该产品的根源?最好在服务器端( gatsby-ssr.js )上。

这样:

  • /product/x/variantDoesnotexist/=> /product/x
  • //product/x/* => /product/x/( * *不是有效的URL零件)
  • /product/y/variantDoesnotexist/=> /product/y/
  • ...

到目前为止仅找到了客户端解决方案,其中包括检查404页模板中的检查路径和进行有条件的 window.location.location.assign 。这不是最佳的,因为它在重定向之前闪烁404页,并且不执行302/301重定向。

Given a Gatsby application with dynamically generated product urls on build:

  • /product/x/
  • /product/x/variant1/
  • /product/x/variant2/
  • /product/y/
  • /product/y/variant1/
  • ...

Is there a way to automatically cause access to non-existing sub-urls of each product to redirect to the root of that product? Preferably on the server-side (gatsby-ssr.js).

Like this:

  • /product/x/variantdoesnotexist/ => /product/x/
  • /product/x/* => /product/x/ (When * is not a valid url part)
  • /product/y/variantdoesnotexist/ => /product/y/
  • ...

Only found a client-side solution so far, which includes checking path in the 404 page template and doing a conditional window.location.assign. This is not very optimal as it flashes the 404 page before redirecting and does not perform a 302/301 redirect.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

始终不够爱げ你 2025-01-30 09:15:25

您可以在 gatsby-node.js 中使用 createredirect 操作:

exports.createPages = async ({ graphql, actions }) => {
    const { createRedirect } = actions;
    
    createRedirect({
    fromPath: `/product/*/foo`,
    toPath: `/product/*`,
  });
}

根据需要对其进行调整,您可以在 createredirect 中使用当前的重定向规则。

请记住,在 createPages 中是创建所有动态页面的地方,因此您拥有所有可用的slug和路径来使您的动态重定向。

更多详细信息:

You can use createRedirect action in the gatsby-node.js:

exports.createPages = async ({ graphql, actions }) => {
    const { createRedirect } = actions;
    
    createRedirect({
    fromPath: `/product/*/foo`,
    toPath: `/product/*`,
  });
}

Tweak it as you wish, you can use your current redirects rules within createRedirect.

Keep in mind that in createPages is where you create all dynamic pages hence you have all the slugs and paths available to make your dynamic redirects.

More details: https://support.gatsbyjs.com/hc/en-us/articles/1500003051241-Working-with-Redirects-and-Rewrites

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文