Cloudflare

Setting up Traffic Splitting with Cloudflare

Setup

To use Traffic Splitting with Cloudflare you will need to deploy a new Cloudflare Worker. This Worker will manage and direct traffic flow between Glopal Proxy and your service Origin.

Create a Worker

  1. Log in to the Cloudflare dashboard and select your account.

  2. Select Workers & Pages > Create application.

  3. Select Create Worker > Deploy.

Create a rewrite rule

In your Cloudflare dashboard, find and click on the "Workers" app. Click on "Create a Worker". This will open the Workers editor where you can write and deploy your script - in the Workers editor, you'll find a pre-filled script. Delete it.

  1. Copy the script and Paste it into the Workers editor.

  2. Make sure to replace GLOPAL_ENDPOINT placeholder with the value you receive from Glopal and that PATTERN is a regular expression describing list of in-scope paths you want to delegate to Glopal.

app.js
const GLOPAL_BACKEND_HOSTNAME = 'GLOPAL_ENDPOINT';
const GLOPAL_PATHNAMES_REGEXP = new RegExp('^\/(PATTERN)($|[:/?])');

addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);
  if (!url.pathname.match(GLOPAL_PATHNAMES_REGEXP)) {
    return fetch(request);
  }
  const newReq = new Request(request);
  newReq.headers.set('X-Forwarded-Host', url.hostname);
  url.hostname = GLOPAL_BACKEND_HOSTNAME;
  url.protocol = 'https:';
  return await fetch(url.href, newReq);
}

Testing your rule

To ensure the rule works as expected, conduct a series of tests by visiting URLs that should be affected by the rule and confirming that they are rewritten correctly.

That's it! You have now created a URL rewrite rule in Cloudflare.

Last updated