Hi! I’m new to the workers scripts and learning to transfer some of our use cases to the cloud. In NGINX, we have a link redirector that redirects based on the query string, i.e:
https://www.example.com/redirector
For example, if this link will receive:
https://www.example.com/redirector/?url=https://sample1.com/path1¶m2=val2¶m3=val3
redirect it to: https://tracker1.com?url=https://sample1.com/path1¶m2=val2¶m3=val3
https://www.example.com/redirector?param1=val1&url=https://sample2.com/path2¶m3=val3
redirect it to: https://tracker2.com?param1=val1&url=https://sample2.com/path2¶m3=val3
else return a 404
We have this system set up in NGINX with regex matching on the values of the url parameter. I’m wondering how to implement this using a worker script as this should lower the latency. A simple script would be appreciated. Thanks for any nudge on the right direction!
Yes we did. Here it is if this will be useful to you:
addEventListener('fetch', event => {
event.respondWith(myRedirect(event.request))
})
async function myRedirect(request) {
let addr = new URL(request.url)
let qs = addr.search
// Assuming your GET parameter is "param" (i.e. ?param=value)
let qs_val = addr.searchParams.get('param')
// If "param" has value...
if (qs_val) {
if (qs_val.includes('text-to-search-here'))
return new Response('', {status: 303, headers: {'Location': 'https://example.com/' + qs}})
else if (qs_val.includes('another-text-to-search-here'))
return new Response('', {status: 303, headers: {'Location': 'https://another-example.com/' + qs}})
else
return new Response('', {status: 303, headers: {'Location': 'https://www.majlovesreg.one/tag/code'}})
}
else
return new Response('', {status: 303, headers: {'Location': 'https://www.majlovesreg.one/'}})
}