I had a scenario where I had to use a cloudflare worker to redirect one page to another, but, I also had to do the following:

  • Display a nice website saying “We will redirect you shortly” with a nice company logo
  • The original and destination URL segments has to be kept in tact.
    • For example, if the source URL is https://sourceurl.com/a/b/c?d=123 the destination URL must be https://destinationurl.com/a/b/c?d=123

Cloudflare Worker Code

  • First we get the URL segments and query parameters from our incoming URL
  • Then we build a new URL using those segments and query parameters
  • Then we create our HTML (you can put anything in here) and also put in the client side Javascript that will redirect us to our new page

Apart from the above, the following will be useful as well:

  • Send back a no-cache header
  • Look up a value from a Worker KV (Cloudflare’s keystore). For this to work, remember to bind the worker to the keystore. You do this in the worker settings
    • This is needed to e.g. check what the first URL segment is, and look up a value where you should redirect to for dynamic redirects
export default {
  async fetch(request, env, ctx) {

	//lets send back some no cache headers
	let modifiedHeaders = new Headers()
	modifiedHeaders.set('Content-Type', 'text/html;charset=UTF-8')
	modifiedHeaders.append('Pragma', 'no-cache')

	//get key from cache
	//TODO: Remember to bind this worker to the KV store. You do this in the worker settings
	let kvValue = await env.worker_nice_redirect.get("my_test_key");

    //Get the original URL segments and query parameters from the source URL
    const base = "https://destinationurl.com";
    const url = new URL(request.url);
    const { pathname, search } = url;

    //Build the destination URL using the URL segments and query parameters we got from above
    const destinationURL = `${base}${pathname}${search}`;

	//Build the basic HTML website that we will send back
    const html = `<!DOCTYPE html>
		<body onload="redirectToPBI()">
		  <h1>Hello there Obi Wan: KV: ${kvValue}</h1>
		  <p>This markup was generated by a Cloudflare Worker. You will redirect in 5 seconds.</p>
      <script type="text/javascript">
        function redirectToPBI() {
          setTimeout(doTheRedirect, 5000);
        function doTheRedirect() {
          document.location.href = "${destinationURL}";

	//Send back the HTML response which will be our HTML and Javascript redirect code
    return new Response(html, {
		headers: modifiedHeaders,
		status: 200

Then we create our DNS A record if we have to.

Then we assign this worker to this new DNS record

Assign worker to DNS record
Categories: General Coding