Forward Child URL to another based on User-Agent


#1

I am wondering if anyone can help. I am wanting to see if I can use Workers to redirect a request using Cloudflare from one url to another based on the user-agent value.

I have two subdomains
https://one.example.com
https://two.example.com

I wanted users to use the first URL only, one.example.com, so this way there is no confusion on which url to use for which access method in addition, the two urls have different security controls applied to I would want everyone to go through the main url versus two.example.com as it would bypass some of the security controls.

There are two modes to access the website, one is a browser and another using a special Application called Atoms and tags the user-agent with the same. What I need to do is redirect the application to the second URL, two.example.com, while everything else is sent through the first URL.

With the application, it uses a URL entered when launching to find the web server so I am not sure if I can redirect the traffic based on the user-agent matching the regex for “Atoms”. This is what I have so far but

addEventListener(‘fetch’, event => {
event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
const redirTo = “https://two.example.com

const ua = request.headers.get(“user-agent”)
if (ua && ua.match(/^Atoms.1.3/)) {
return new Response(
“Client Application Redirect”,
{
status: 307,
headers: new Headers({“Location”: redirTo})
}
)
} else {
return fetch(request)
}
}

Any assistance would be great. I am still new to this and while its exiting, getting frustrated probably because I am still learning.