GatsbyJS - Resolve Page URLs With and Without ".html" Suffix

Viewed 320

I'm in a bit of an unfortunate position where the design choices of someone years ago are now affecting my rebuild of a website. Basically, way back when the site was originally created the designer pushed to have all URLs be fully explicit with the .html extensions (eg website.com/index.html). I am currently in the process of rebuilding the site with Gatsby and it has come to my attention that we need to continue resolving those old URLs as they are still scattered around the internet in the form of links. But the owner would like to move away from those URLs going forward, so basically I just need to support resolving them for backwards compat.

I have been working with the onCreatePage function and can get it to resolve the .html links like so:

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);
    }
};

But unfortunately that only resolves the .html URLs, not plain urls with no .html suffix.

Is there a way I can achieve this? Should I be looking at a different API than onCreatePage?

UPDATE: Just found the gatsby-plugin-client-side-redirect and have tried the following:

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 });
    }
};

The console is outputting the correct old URLs but it is not redirecting... not sure what I'm doing wrong...

1 Answers

createRedirect works, it just doesn't work while running the site in development mode. You need to do a full build and serve locally if you want to observe the redirects working correctly locally.

Final code was:

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
        });
    }
};
Related