Limited Time Free!  Experience website acceleration and advanced security protection!
Get Started Now 

Referer-based Hotlink Protection

Referer anti-leeching technology is a strategy adopted by websites to protect their resources and prevent other websites from illegally using their content. 

In this example, an Edge Function is used to enforce Referer hotlink protection by checking the Referer field in the HTTP request header to determine the request's origin.

Code

async function handleRequest(request) {  
  const referer = request.headers.get('Referer');

  if (!referer) {
    return new Response('Invalid referer', {
      status: 403,
    });
  }
  
  const refererRegExp = new RegExp(`^https:\/\/playground\.edgeone\.ai\/?.*`);
  
  if (!refererRegExp.test(referer)) {
    return new Response('Invalid referer', {
      status: 403,
    });
  }

  return new Response('Valid referer', {
    status: 403,
  });
}

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

Preview

If the referer is incorrect, access is denied.

Xnip2024-07-16_11-58-03.png

If the referer is correct, access is granted.

Xnip2024-07-16_11-57-16.png

 

References