gpt4 book ai didi

GatsbyJS - 解析带有和不带有 ".html"后缀的页面 URL

转载 作者:行者123 更新时间:2023-12-04 09:49:37 30 4
gpt4 key购买 nike

我处于一个有点不幸的位置,几年前某人的设计选择现在正在影响我重建网站。基本上,早在网站最初创建时,设计者就插入所有 URL 完全显式地使用 .html 扩展名(例如 website.com/index.html)。我目前正在用 Gatsby 重建网站,我注意到我们需要继续解析那些旧的 URL,因为它们仍然以链接的形式散布在互联网上。但是所有者希望远离这些 URL,所以基本上我只需要支持解析它们以进行向后兼容。

我一直在使用 onCreatePage 函数,可以让它解析 .html 链接,如下所示:

exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions;
console.log(actions);

// Create resolvers for all pages with .html in URLs
if (!page.path.endsWith(".html")) {
const isIndex = page.path === "/";
page.matchPath = isIndex
? page.path + "/index.html"
: page.path.replace(/\/$/, ".html");

createPage(page);
}
};

但不幸的是,这只能解析 .html 网址,而不是没有 .html 后缀的普通网址。

有没有办法实现这一目标?我应该查看与 onCreatePage 不同的 API 吗?

更新:
刚刚找到 gatsby-plugin-client-side-redirect并尝试了以下方法:

exports.onCreatePage = async ({ page, actions }) => {
const { createRedirect } = actions;

// Create resolvers for all pages with .html in URLs
if (!page.path.endsWith(".html")) {
const isIndex = page.path === "/";
const legacyUrl = isIndex
? page.path + "/index.html"
: page.path.replace(/\/$/, ".html");

console.log("legacyUrl::", legacyUrl);
createRedirect({ fromPath: legacyUrl, toPath: page.path, isPermanent: true });
}
};

控制台正在输出正确的旧 URL,但它没有重定向......不知道我做错了什么......

最佳答案

createRedirect工作,它只是在开发模式下运行网站时不起作用。如果您想观察重定向在本地正常工作,则需要进行完整构建并在本地提供服务。

最终代码是:

exports.onCreatePage = async ({ page, actions }) => {
const { createRedirect } = actions;

// Create resolvers for all pages with .html in URLs
if (!page.path.endsWith(".html")) {
const isIndex = page.path === "/";
const legacyUrl = isIndex
? "/index.html"
: page.path.replace(/\/$/, ".html");

createRedirect({
fromPath: legacyUrl,
toPath: page.path,
isPermanent: true
});
}
};

关于GatsbyJS - 解析带有和不带有 ".html"后缀的页面 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62028058/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com