我现在处于一个不幸的境地,多年前某人的设计选择现在影响了我对一个网站的重建。基本上,早在网站最初创建的时候,设计者就要求所有的URL都用.html扩展名(如site.comindex.html)。我目前正在用Gatsby重建网站,我注意到我们需要继续解析那些旧的URL,因为它们仍然以链接的形式散落在互联网上。但是老板希望今后不再使用这些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 URL,而不能解析没有.html后缀的普通URL。
有什么方法可以实现这个目标吗?我是否应该寻找一个不同于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 });
}
};
控制台输出的是正确的旧网址,但没有重定向... 不知道我做错了什么... ...
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
});
}
};