How to Redirect Affiliate Links with CloudFlare Workers (with Proper HTTP Headers for SEO)

There are many advantages of redirecting affiliate links with Cloudflare Workers.

  • It’s super fast. Done at the Edge. Mines does backend redirect processing under 2ms.
  • you cloak your affiliate links without a plugin that saves resources from your server.
  • Cloudflare Workers has a free plan for up to 100,000 requests per day.

I wanted to cloak affiliate links without a plugin because I was moving away from WordPress. I was moving to Hugo’s static site generator and Cloudflare Pages.

I am back on WordPress now but still use Cloudflare for affiliate link redirection.

When I first tried, I ran into some problems.

I made some research and came up with a solution that I will share with you in this post.

I read the documentation of Cloudflare Workers and ServiceWorker API to get things work. So, here’s the usual disclaimer: By following, you agree that I am not liable to you for any direct and indirect damages. In doubt? Hire a developer to do it for you. Not to scare you, anyway.

Agreed? Let’s move on.

Affiliate Disclosure: This page contains affiliate links from which I may earn a commission per sale.

I did not want my workers to check every URL but just affiliate link redirects. So, I use the path https://goaskeustache.com/goto/ for all my affiliate links.

I recommend that you set up an identifier for your affiliate links. The most commons are goto, go, recommends, and out.

Then, I did not use the Response.redirect function. I could not find a way to add the X-Robots-Tag HTTP Header to prevent search engines to index my affiliate links by using it.

So, here’s the code with the fixes to all those problems.

This is the code I added to CloudFlare Workers with my 300+ affiliate links in the redirectMap.

const redirectMap = new Map([
  ["https://goaskeustache.com/goto/2checkout/", "https://www.2checkout.com/referral?r=e230f815a7"],
  ["https://goaskeustache.com/goto/3dcart/", "https://shareasale.com/r.cfm?b=770466&u=941349&m=3609&urllink=&afftrack=0"],
])

async function handleRequest(request) {
  const requestURL = new URL(request.url)
  const path = requestURL.pathname;
  const location = redirectMap.get(path)
  if (location) {
    let response = new Response(null, {
      status: 302,
      statusText: "Found"
    })
    response.headers.set("X-Robots-Tag", "noindex,nofollow")
    response.headers.set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
    response.headers.set("Cache-Control", "max-age=604800")
    response.headers.set("X-Redirect-By", "cloudflare")
    response.headers.set("Response", "302")
    response.headers.set("location", location)
    return response
    }
  // If request not in map, return the original request
  return fetch(request)
}

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

The part of the code that you’ll modify is the Map of affiliate links.

const redirectMap = new Map([
  ["https://goaskeustache.com/goto/2checkout/", "https://www.2checkout.com/referral?r=e230f815a7"],
  ["https://goaskeustache.com/goto/3dcart/", "https://shareasale.com/r.cfm?b=770466&u=941349&m=3609&urllink=&afftrack=0"],
])

On each line, you add the short URL and the real affiliate link you want the user to be redirected to. Pay attention to the comma after each line.

I have 300+ affiliate links and the average backend processing by CloudFlare is 1ms. It’s blazing fast.

How the Affiliate Redirection Code Works

When the worker script is executed, the handleRequest function is called with the request, and the affiliate link to redirect. Eventually, we route the worker to be executed only for affiliate URLs.

The handleRequest function will first remove the domain from the URL to keep only the pathname for comparison. Then it tries to add the destination for that pathname into a variable if it’s in the Map.

const requestURL = new URL(request.url)
  const path = requestURL.pathname;
  const location = redirectMap.get(path)

Then, it checks if the path name is in the list of affiliate links. If it finds it, it creates a new HTTP Response to be sent with a 302 status.

if (location) {
    let response = new Response(null, {
      status: 302,
      statusText: "Found"
    })

It adds the X-Robots-Tag HTTP header and set the value to noindex, nofollow. This way, search engines won’t index your affiliate links.

response.headers.set("X-Robots-Tag", "noindex,nofollow")

It adds another HTTP header, the HSTS HTTP header, to force HTTPS encryption and always use HTTPS.

This line of code can break your website if you don’t use HSTS. However, it is highly recommended to add this security HTTP header to add another layer of security to your website. Otherwise, remove this line.

response.headers.set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")

It adds cache control and a way to check that your link was redirected by Cloudflare.

response.headers.set("Cache-Control", "max-age=604800")
response.headers.set("X-Redirect-By", "cloudflare")

Then, it adds the HTTP Response code: 302.

Finally, it adds the real HTTP header for redirection: location and return the new HTTP Response.

response.headers.set("Response", "302")
response.headers.set("location", location)
return response

The redirection HTTP header receives the destination URL as an argument. So, once the browser receives that response, it will respect the location header and redirect to the affiliate offer.

Otherwise, if the affiliate link does not exist, it forwards the request to be handled by your browser or server. (404 error page or something else)

Here’s the step-by-step process.

1.- You go to your Cloudflare Workers dashboard and create a new Worker Script. Call it whatever you want to remember its purpose (maybe afflink).

Create A Worker on CloudFlare

2.- Add all your affiliate links in const redirectMap = new Map([])using the format of the two default links in the code I added above. Remember to delete the default links because they are mine. They’re just here for reference.

3.- Add the code above, with all your affiliate links and other functions, to your Worker Script and deploy.

4.- Test that it works correctly. Normally, you’ll add one affiliate link to the custom URL given by Cloudflare.

Ex: afflink.domainname.workers.devhttps://goaskeustache.com/goto/partner/.

5.- Add a route to your worker so Cloudflare runs it when an affiliate link is requested.

Route your Worker to Redirect Affiliate Links with Cloudflare

Set the “Request limit Failure Mode” to Open so the worker never blocks the Process even if it fails. (Such as when you run out of limits on the free plan.)

It’s the simple process you can follow to redirect affiliate links with Cloudflare Workers.

It’s ideal if you’re running a static website. However, even if you blog with WordPress, this process will speed up your affiliate redirection. It’s done at the Edge; not by a WordPress PHP function, or your server htaccess.

I set my affiliate redirection script with Cloudflare Workers a month before I moved to Hugo + Cloudflare pages.

Pros of this method

  • You’re not relying on a URL shortener that may add tracking to your redirects and break GDPR rules.
  • Your affiliate links redirect fast, at the EDGE, which may increase conversion in some cases.
  • You’re not relying on PHP or a database which are slower than Edge and prone to attack.
  • Doing a backup is as easy as saving your script file.
  • You can prevent index of your affiliate links via the most recommended method: HTTP Header.

Cons of this method

You have to log into CloudFlare to manage your affiliate links and be careful about the syntax so you don’t break things.

I know some of you will set up something in GitHub to take advantage of automatic git push sync on Cloudflare.

I hope you enjoyed this tutorial.

Use Lasso to manage affiliate links: Lasso is a WordPress plugin for affiliate link management. It checks if affiliate links are broken and display affiliate boxes that may increase the conversion rate. It’s a WordPress plugin, so slower than HTaccess or Cloudflare Worker redirects. It’s for people on WordPress who need a graphic interface.

ClickMagick: This affiliate link manager removes the stress from your server. It also makes it easy to redirect affiliate links with geo-localization. The con of this method is that you get billed by clicks on your links their servers has to process. (Starting at $37/mth for up to 10,000 clicks a month). The pros are that you can protect your links from bots, and do split testing and retargeting.

I stick with Cloudflare workers to manage my affiliate links.

Recommended Reading:

You are here: