Fastly_CDN/CDN_설정

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

CDN_SKY 2023. 5. 22. 11:26

이번에는 GeoIP block 관련해서 JS Compute@Edge로 구현하는 방법에 대해서 포스팅합니다. Edge Dictionaries에 포함되지 않는 Geo Country는 블럭됩니다. Fiddle에 보시면 오른쪽 위에 URL을 입력하는 부분의 밑에 Data populated라는 메뉴가 있으며 해당 메뉴에 Edge Dictionaries 로 구현할 Key와 Value를 입력하실 수 있습니다. 관련 main code는 아래와 같으며, 첨부의 fiddle 도 참고해 주시길 바랍니다. 감사합니다.

 

https://fiddle.fastly.dev/fiddle/b318387a

 

Fiddle - Fastly

 

fiddle.fastly.dev

/// <reference types="@fastly/js-compute" />

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

async function handleRequest(event) {
  // Get the request from the client.
  const req = event.request;
  // Get the client information (geolocation, clientIP)
  const clientGeoCode = event.client.geo.country_code;
  const clientCountryName = event.client.geo.country_name.toUpperCase();
  let fastlyClientIp = event.client.address;

  //set logger
  const logger = fastly.getLogger("logtest"); 

  //set dictionaries
  const geoTable = new ConfigStore('geoip_block'); // edge dictionaries name is geoip_block
  logger.log("◆ fastlyClientIp: " + fastlyClientIp);
  logger.log("◆ clientGeoCode: " + clientGeoCode);
  logger.log("◆ clientCountryName: " + clientCountryName);

  //Get the value from the edge dictionaries
  const geoBan = geoTable.get(clientGeoCode);
  logger.log("◆ geoBan is: " + geoBan);

  //  if geoBan is null, return 403 to the client
  if (geoBan === null){
      return new Response("You can not access to this site from " + clientCountryName, { status: 403 });  
  }

  return fetch(req, {
    backend: "origin_0"
  });
}