Created
May 30, 2024 03:48
-
-
Save steig/b51c9ff67ee5fa2d4c3a3a4c3c0e41d1 to your computer and use it in GitHub Desktop.
Cloudflare 301 redirect based on user agent.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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