Fastly_CDN/CDN_설정

패스틀리(Fastly), Compute@Edge를 사용해 보자 #6

CDN_SKY 2023. 7. 11. 23:45

이번 포스팅에서는 JavaScript compute@edge를 활용해서 부정한 User-Agent를 차단하는 code를 알려드리도록 하겠습니다.

아래의 코드와 Fiddle를 참고해 주세요. 감사합니다.

 

https://fiddle.fastly.dev/fiddle/2b347a66

 

Fiddle - Fastly

 

fiddle.fastly.dev

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

async function handleRequest(event) {
  // Get the request from the client.
  const req = event.request; 
  const userAgent = req.headers.get("user-agent");

  // Set logger
  const logger = fastly.getLogger("logtest");
  logger.log("User-Agent is: " + userAgent);

  //const blockedUserAgent = "blackwidow";
  const blockedUserAgent = /80legs|black\ widow|blackwidow|prowebwalker|pymills\-spider|AhrefsBot|PiplBot|GrapeshotCrawler2\.0|grapeFX|SearchmetricsBot|SemrushBot|rogerbot|MJ12bot|Owlin\ bot|Lingewoud\-550\-Spyder|Wappalyzer/i;

  // Lookup table and get the expiration time for the IP
  if (userAgent.match(blockedUserAgent)){
      return new Response("Your UA is not allowed", { status: 403 });
  }
  
  // Send the request to `origin_0`.
  const backendResponse = fetch(req, {
    backend: "origin_0"
  });

  // Send the backend response back to the client.
  return(backendResponse);
};