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. This example determines the request sources by checking the Referer field in the HTTP request header. You can flexibly customize the matching rules for this Referer. If the Referer does not exist or does not match the allowed domain list, the Edge Functions will reject the request and return a 403 status code.

Sample Code

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

  // If the Referer is empty, access is denied
  if (!referer) {
    return new Response(null, { status: 403 });
  }
  
  const urlInfo = new URL(request.url);
  const refererRegExp = new RegExp(`^https?:\/\/${urlInfo.hostname}\/t-[0-9a-z]{10}\/.*`)
  
  // If the Referer is not on the allowlist, access is denied
  if (!refererRegExp.test(referer)) {
    return new Response(null, { status: 403 });
  }

  // Normal request, access EdgeOne node cache or origin-pull
  return fetch(request);
}

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

Example Preview

Enter the URL that matches the Edge Function triggering rules in the address bar of the browser on the PC end and mobile end (e.g., https://example.com/images/ef-1.jpeg) to preview the example effect.

  • 1. HTTP request header Referer is https://example.com/t-0123456789/page, and the Edge Function responds normally to the image.

Enter the URL that matches the Edge Function triggering rules in the address bar of the browser on the PC end and mobile end (e.g., https://example.com/images/ef-1.jpeg) to preview the example effect.

18.1.png

  • 2. HTTP request header Referer is not on the allowlist, and the Edge Function identifies it as a leeching link and responds with a 403 status code.

18.2.png

Related References

  1. Runtime APIs: Fetch
  2. Runtime APIs: Headers
  3. Runtime APIs: Response