Skip to content

Instantly share code, notes, and snippets.

@steig
Created May 30, 2024 03:48
Show Gist options
  • Select an option

  • Save steig/b51c9ff67ee5fa2d4c3a3a4c3c0e41d1 to your computer and use it in GitHub Desktop.

Select an option

Save steig/b51c9ff67ee5fa2d4c3a3a4c3c0e41d1 to your computer and use it in GitHub Desktop.
Cloudflare 301 redirect based on user agent.
export default {
async fetch(request) {
const botUserAgents = new Map([
[/botUserAgent1/i, "bot=bot1"],
[/botUserAgent2/i, "bot=bot2"],
[/botUserAgent3/i, "bot=bot3"]
]);
const userAgent = request.headers.get('User-Agent');
if (userAgent) {
for (const [regex, utmParam] of botUserAgents) {
if (regex.test(userAgent)) {
// Construct the new URL with the UTM parameter
const url = new URL(request.url);
const [key, value] = utmParam.split('=');
url.searchParams.set(key, value);
// Perform a 301 redirect
return Response.redirect(url.toString(), 301);
}
}
}
return fetch(request);
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment