This page contains affiliate links from which I'll receive commissions!
.
In Category Affiliate Marketing

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. Mine’s does backend redirect processing under 2ms.
  • You cloak your affiliate links without a plugin that saves resources from your server.
  • Cloudflare Workers has a generous 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’ free hosting.

I leave beyond the server resources requirements of WordPress and use Cloudflare for affiliate link redirection.

When I first tried, I ran into some problems.

  • The example of code provided by CloudFlare for bulk-redirect uses sub-requests. Not ideal for my quotas. Each link redirection would cost 2 requests.
  • The code used the HTTPResponse.Redirect function. So, I could not add HTTP headers for SEO.

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

I am a programmer and digital marketer. I read the documentation of Cloudflare Workers and ServiceWorker API to get the function to 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.

Let’s move on.

SEO Optimized Affiliate Link Redirect with Cloudflare Workers

affiliate link cloaking with CloudFlare Workers.

Done wrong, affiliate link management can ruin your site rankings. That’s why I do this setup to be SEO optimized.

Also, to efficiently use the 100,000 free daily requests, I did not want my workers to check every URL, but just affiliate link redirects. So, I use the path /goto/ for all my affiliate links.

I recommend that you set up an identifier for your affiliate links. The most commonly used 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 from indexing my affiliate links by using it.

Note: We updated this tutorial to use Cloudflare Module Workers that replace Service Workers and provide updated screenshots of the modified interface.

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

The Code to cloak affiliate links with Cloudflare Workers

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

export default {
  async fetch(request) {
    const externalHostname = "examples.cloudflareworkers.com";

    const redirectMap = new Map([
  ["/goto/appsumo/", "https://appsumo.8odi.net/askeustache"],
  ["/goto/cloudways/", "https://platform.cloudways.com/signup?id=297916&coupon=WELCOME26&data2=newyearpromo"],
  ["/goto/convertkit/", "https://partners.kit.com/2870nx18vqpm"],
  ["/goto/scalahosting/", "https://www.scalahosting.com/#askeustche"],
]);

    const requestURL = new URL(request.url);
    let path = requestURL.pathname;
	if (path.substr(-1) != '/') path += '/';
    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", "no-store")
		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);
  },
};

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

const redirectMap = new Map([
  ["/goto/appsumo/", "https://appsumo.8odi.net/askeustache"],
  ["/goto/cloudways/", "https://platform.cloudways.com/signup?id=297916&coupon=WELCOME26&data2=newyearpromo"],
  ["/goto/convertkit/", "https://partners.kit.com/2870nx18vqpm"],
  ["/goto/scalahosting/", "https://www.scalahosting.com/#askeustche"],
]);

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.

PS: I have an upgraded version of this code in my free course on affiliate link management with Cloudflare. If you need custom 404 error pages or deep-linking, take the course now. It uses a different link format.

["/goto/cloudways/", (v) => `_https://www.cloudways.com/?id=297916&coupon=WELCOME26`]

The (v) is a function I explain in the course for advanced link management and centralized control.

I have 100+ affiliate links, and the average backend processing by CloudFlare is 2ms. 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 sets 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")

Next, it adds the HTTP Response code: 302.

Finally, it adds the real HTTP header for redirection: location, and returns 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.- Connect to your Cloudflare account, and in the sidebar, under Compute, click on “Workers & Pages”.

Create A Worker on CloudFlare

2.- On the right, locate the “Create Application” button to create a new Worker Script. Call it whatever you want to remember its purpose (maybe afflink).

3.- When asked to choose how you’ll start, if you connect a Git account or start from a template, choose “Start with Hello World”. Then, on the next page, click the “Edit code” button to remove the default code and add the Workers code above.

Choose Start with Hello World

4.- 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.

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

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

Ex: afflink.domainname.workers.dev/goto/partner/.

7.- 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.)

You can Cloak Affiliate links with Cloudflare Workers Script Now

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’s 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, add to your server’s usage cost, and are prone to attack.
  • Doing a backup is as easy as saving your script file.
  • You can prevent the indexing 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.

Other Options to Manage Affiliate Links

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

Also, there are some other options worth considering.

Use Lasso to manage affiliate links: Lasso is a WordPress plugin for affiliate link management. It checks if affiliate links are broken and displays 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. I use them for Amazon Associates only for the API access.

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. (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.

I stick with Cloudflare Workers to manage my affiliate links.

Recommended Reading:

Read next:

About the author: