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 Redirect
s 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?
Use a slightly more relaxed regex.