Skip to content

Instantly share code, notes, and snippets.

@chriskyfung
Created February 8, 2025 07:59
Show Gist options
  • Save chriskyfung/90f561358120ffac58b13d01035542f1 to your computer and use it in GitHub Desktop.
Save chriskyfung/90f561358120ffac58b13d01035542f1 to your computer and use it in GitHub Desktop.
Implement country-based redirection in Cloudflare Workers
/**
* 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))
})
@chriskyfung
Copy link
Author

Example Cloudflare Worker Script for Request Handling and Redirection

This script provides a basic Cloudflare Worker structure to handle HTTP requests and generate responses.

  1. Request Handling and Redirection

    • If the pathname is / (for production) or /dev/ (for development), the script constructs a target URL and redirects the request accordingly.
  2. Country-Based Redirection

    • Redirect users to specific URLs based on their country of origin using the cf.country property provided by Cloudflare's request object.
    • If the auto-detect query parameter is set to 1, the script checks the requester's country (e.g., US, AU, HK, SG) and adds custom parameters to the redirection URL.
  3. Error Handling

    • It returns a 500 Internal Server Error response if the pathname is neither / nor /dev/.

Here is the visualization of the script's routing logic:

stateDiagram-v2
    [*] --> PathCheck
    PathCheck : Pathname?
    PathCheck --> ProductionPath: /
    PathCheck --> DevPath: /dev/
    PathCheck --> ServerError: Other Path
    ProductionPath : Construct Target URL for Production
    DevPath : Construct Target URL for Development
    ServerError : Internal Server Error
    ProductionPath --> SearchParamsCheck : Search Parameters?
    SearchParamsCheck --> AutoDetect: auto-detect=1
    SearchParamsCheck --> RedirectWithSearch: No auto-detect
    SearchParamsCheck --> RedirectNoSearch: No Search
    AutoDetect --> CountryCheck: Country Check
    CountryCheck --> RedirectCustomParams: US, AU, HK, SG
    CountryCheck --> RedirectWithoutCustomParams: Other
    RedirectWithSearch : Redirect with Search Params
    RedirectNoSearch : Redirect to Target URL
    RedirectCustomParams : Redirect with Custom Params
    RedirectWithoutCustomParams : Redirect to Target URL
    DevPath --> DevSearchParamsCheck : Search Parameters?
    DevSearchParamsCheck --> DevAutoDetect: auto-detect=1
    DevSearchParamsCheck --> DevRedirectWithSearch: No auto-detect
    DevSearchParamsCheck --> DevRedirectNoSearch: No Search
    DevAutoDetect --> DevCountryCheck: Country Check
    DevCountryCheck --> DevRedirectCustomParams: US, AU, HK, SG
    DevCountryCheck --> DevRedirectWithoutCustomParams: Other
    DevRedirectWithSearch : Redirect with Search Params
    DevRedirectNoSearch : Redirect to Target URL
    DevRedirectCustomParams : Redirect with Custom Params
    DevRedirectWithoutCustomParams : Redirect to Target URL
Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment