Created
February 8, 2025 07:59
-
-
Save chriskyfung/90f561358120ffac58b13d01035542f1 to your computer and use it in GitHub Desktop.
Implement country-based redirection in Cloudflare Workers
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
/** | |
* Welcome to Cloudflare Workers! This is your first worker. | |
* | |
* - Run "npm run dev" in your terminal to start a development server | |
* - Open a browser tab at http://localhost:8787/ to see your worker in action | |
* - Run "npm run deploy" to publish your worker | |
* | |
* Learn more at https://developers.cloudflare.com/workers/ | |
*/ | |
// export default { | |
// async fetch(request, env, ctx) { | |
// return new Response('Hello World!'); | |
// }, | |
// }; | |
const base = 'https://example.com'; | |
const project = { | |
prod: '/', | |
dev: '/staging' | |
}; | |
const relpath = '/assets/iframe-for-amp.html'; | |
const customParams = '?option=1'; | |
const statusCode = 302; | |
async function handleRequest(request) { | |
const url = new URL(request.url); | |
const { pathname, search, searchParams } = url; | |
// Return server error if path is not equal to `/` or `/dev` | |
if (pathname !== '/' && pathname !== '/dev/') { | |
return new Response('Internal Server Error', { status: 500 }); | |
} | |
const targetURL = base + project[pathname === '/' ? 'prod' : 'dev'] + relpath; | |
if (searchParams.get('auto-detect') === '1') { | |
// Check for country-based redirect | |
const countryList = ['US', 'AU', 'HK', 'SG']; // Example country list | |
if (countryList.includes(request.cf.country)) { | |
return Response.redirect( targetURL + customParams, statusCode); | |
} | |
} | |
if (search) { | |
return Response.redirect(targetURL + search, statusCode); | |
} | |
return Response.redirect(targetURL, statusCode); | |
// // Pass through other requests | |
// return fetch(request); | |
} | |
addEventListener("fetch", async event => { | |
event.respondWith(handleRequest(event.request)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Cloudflare Worker Script for Request Handling and Redirection
This script provides a basic Cloudflare Worker structure to handle HTTP requests and generate responses.
Request Handling and Redirection
/
(for production) or/dev/
(for development), the script constructs a target URL and redirects the request accordingly.Country-Based Redirection
cf.country
property provided by Cloudflare's request object.auto-detect
query parameter is set to1
, the script checks the requester's country (e.g., US, AU, HK, SG) and adds custom parameters to the redirection URL.Error Handling
/
nor/dev/
.Here is the visualization of the script's routing logic: