How to redirect all the route paths starting with foo to paths starting with bar

128 views Asked by At

The examples below demonstrate what I want to achieve:

/foo => /bar
/foo/a => /bar/a
/foo/a/b => /bar/a/b
/foo/a/b/c => /bar/a/b/c
...

I've tried <Redirect from="/foo/(.*)" to="/bar/(.*)" />, but it didn't work when the wildcard matches two or more path segments. To be specific, /foo/a/b would become /bar/a%2F/b rather than /bar/a/b.

The only feasible way I've thought of is use a function to generate multiple Redirects like below:

function generate(fromPrefix, toPrefix, maxLevel = 5) {
  return Array(maxLevel)
    .fill()
    .map((_, i) => {
      const wildcards = Array(maxLevel - i)
        .fill('(.*)')
        .join('/');
      const from = `${fromPrefix}/${wildcards}`;
      const to = `${toPrefix}/${wildcards}`;
      return <Redirect from={from} to={to} />;
    });
}

Is there a better way to do this?

1

There are 1 answers

0
Drew Reese On BEST ANSWER

Use a slightly more relaxed regex.

<Redirect from="/foo*" to="/bar*" />

Edit how-to-redirect-all-the-route-paths-starting-with-foo-to-paths-starting-with-bar