Skip to content

Instantly share code, notes, and snippets.

@timkelty
Last active May 2, 2024 18:10
Show Gist options
  • Save timkelty/f8100454531cee11eb6ee9d57470c2e4 to your computer and use it in GitHub Desktop.
Save timkelty/f8100454531cee11eb6ee9d57470c2e4 to your computer and use it in GitHub Desktop.
const original = new URL('https://foo.com/boo/bar/baz/boo?qux');
const kvData = {};
kvData.redirects = [
{
// expected result: https://foo.com/boo/baz/boo
from: '^/(foo|boo)/bar/(.*)',
to: '/$1/$2',
status: 301,
pathOnly: true,
},
{
// expected result: https://www.foo.com/foo/bar/baz/boo?qux
from: 'https://foo.com/(.*)',
to: 'https://www.foo.com/$1',
status: 302,
pathOnly: false,
},
]
function handleRedirects() {
for (const redirect of kvData.redirects) {
const stringToMatch = redirect.pathOnly ? original.pathname : original.href;
const matches = stringToMatch.match(new RegExp(redirect.from));
if (matches?.length) {
const replaced = redirect.to.replace(new RegExp('\\$(\\d)', 'g'), function(match, index) {
return matches[index]
});
const location = new URL(replaced, original);
console.log(location);
return new Response(null, {
status: redirect.status,
headers: {
Location: location,
},
});
}
}
}
handleRedirects()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment