Edge 함수를 사용한 HTTP 요청 필터
AEM Edge 함수를 사용하여 HTTP 요청 필터링을 구현하여 요청을 다시 작성하거나 리디렉션하거나 HTTP 응답을 수정하는 방법을 알아봅니다.
Edge 함수를 사용하여 HTTP 요청을 필터링하는 경우
AEM Edge 함수는 요청 및 응답이 원본 또는 클라이언트에 도달하기 전에 고급 처리를 수행하는 역방향 프록시로 작동할 수 있습니다.
두 가지 시나리오는 다음과 같습니다.
요청이 원본에 도달하기 전에 조정
원점으로 이동하는 트래픽을 가로채서 다음 작업을 수행합니다.
- 요청 원본, 경로 또는 쿼리를 다시 작성하십시오. 원본을 올바른 리소스로 받도록 요청을 다른 백엔드, 경로 또는 쿼리 문자열로 라우팅합니다.
- 요청 헤더를 다시 씁니다. 요청이 원점에 도달하기 전에 헤더를 추가, 제거 또는 수정합니다. 예를 들어, 원본에서 기대하는 지역 또는 액세스 헤더를 추가하거나, 원본에서 무시하는 헤더를 제거하거나, 헤더 값을 변경하여 요청 동작을 변경할 수 있습니다.
클라이언트에 도달하기 전에 응답을 수정합니다.
클라이언트(방문자)로 돌아가는 길에 트래픽을 가로채서 다음 작업을 수행합니다.
- 응답을 HTML으로 변경합니다. 페이지가 브라우저에 도달하기 전에 JavaScript, 개인화된 콘텐츠, 링크 다시 작성 또는 머리글과 바닥글에 결합을 주입합니다.
- 가장자리에서 리디렉션합니다. 특히 리디렉션 규칙에 프로그래밍 방식 논리가 필요한 경우 CDN에서 큰 레거시-새 URL 리디렉션 집합을 제공합니다.
- 요청 컨텍스트별로 개인화합니다. 공개 방문자에 대해 지리적 위치, 장치 또는 대상별로 페이지 또는 페이지 섹션을 변경합니다. 이는 작성자 트래픽이 아닌 사이트 도메인의 게시 트래픽에 적용됩니다.
HTTP 요청 필터링 구현
HTTP 요청 필터링은 두 개의 파일을 사용합니다. config/cdn.yaml 파일은 가로채고 AEM Edge 함수로 라우팅할 트래픽을 결정합니다. src/index.js 파일이 요청 또는 응답 조정을 수행합니다.
원본 선택기와 함수 이름이 정렬되어야 합니다. edgeFunctions.yaml이(가) my-edge-function을(를) 선언하면 원본 선택기는 cdn.yaml에서 edgefunction-my-edge-function을(를) 사용합니다.
CDN 필터 구성
# config/cdn.yaml (origin selector excerpt)
kind: "CDN"
version: "1"
data:
originSelectors:
rules:
- name: route-to-edge-function
when:
allOf:
- { reqProperty: tier, equals: "publish" } # publish traffic only; skip author
- { reqProperty: domain, equals: "www.example.com" } # your site hostname
- { reqProperty: originalPath, matches: "(/[^./]+|\\.html|/)$" } # page URLs; skip static assets (.css, .js, images, fonts)
# - { reqProperty: method, in: ["GET", "HEAD"] } # optional: navigation only; skip POST, PUT, and other methods with bodies
- { reqHeader: x-edgefunction-request, exists: false } # skip loopback requests to prevent infinite loops
action:
type: selectAemOrigin
originName: edgefunction-my-edge-function # edgefunction-<name-of-the-function>
조건이 실패하면 요청이 AEM Edge 기능에 도달하지 않습니다. 함수에서 필요로 하는 최소 조건으로 시작하고 더 많은 을 추가하여 라우팅을 더 정밀하게 만듭니다. 지원되는 모든 속성 및 연산자에 대해서는 원본 선택기를 참조하십시오.
핸들러 구현
모든 AEM Edge 함수는 가져오기 이벤트 핸들러를 등록합니다. 핸들러를 사용하여 요청이 원점에 도달하기 전에 조정하거나, 응답이 클라이언트에 도달하기 전에 수정하거나, 두 가지 모두를 수행합니다.
다음 코드 조각은 AEM Edge 함수에서 요청 필터링 및 응답 수정을 보여 줍니다.
// src/index.js
addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));
async function handleRequest(event) {
const req = event.request;
const url = new URL(req.url);
try {
// ------------------------------------------------------------
// --- Request filtering: adjust before origin ---
// ------------------------------------------------------------
// Example: Rewrite origin, path, or query
// Replace origin based on some criteria such as path or query
const newOriginRequest = new Request(`https://origin.example.com${url.pathname}${url.search}`);
const newOriginResponse = await fetch(newOriginRequest);
// Return the new origin response
return newOriginResponse;
...
// Example: Rewrite request headers before reaching the origin
// Add or modify headers before the request reaches the origin, like adding an authorization token based on exchange with an external service.
const originRequest = new Request(req, {
headers: new Headers({ ...Object.fromEntries(req.headers), "Authorization": "Bearer <token>" }),
});
const originResponse = await fetch(originRequest);
return originResponse;
...
// ------------------------------------------------------------
// --- Response filtering: modify before client ---
// ------------------------------------------------------------
// Example: Change response HTML (fetch from origin, transform the body)
// Fetch the response from the origin, transform the body, and return the transformed response.
const originRequest = new Request(`https://origin.example.com${url.pathname}`);
const originResponse = await fetch(originRequest);
const transformedHtml = transformHtml(await originResponse.text());
return new Response(transformedHtml, { status: 200, headers: originResponse.headers });
...
// Example: Redirect at the edge
// Redirect the client to a new path, like a legacy URL to a new URL.
return Response.redirect("https://www.example.com/new-path", 301);
...
// Example: Personalize by request context (geo, device, or audience)
// Fetch the response from the origin, personalize the body, and return the personalized response.
const originRequest = new Request(`https://origin.example.com${url.pathname}`);
const originResponse = await fetch(originRequest);
const personalizedHtml = personalizeHtml(await originResponse.text());
return new Response(personalizedHtml, { status: 200, headers: originResponse.headers });
return new Response("Not implemented", { status: 501 });
} catch (err) {
console.log(err);
return new Response("Error", { status: 500 });
}
}
주요 사항:
cdn.yaml의 when + allOf은(는) AEM Edge 함수와 일치하는 트래픽만 라우팅합니다.fetch() 앞에 다른 원본, 경로, 쿼리 또는 머리글을 사용하여 원본 Request을(를) 만듭니다.Response을(를) 반환합니다.fetch() 호출에 대해 sentinel 헤더를 설정합니다.디자인 지침
- 필터를 실용적인 만큼 좁게 유지하십시오.
- 탐색 함수를
GET및HEAD(으)로 제한하십시오. - 내부
fetch()호출에서 sentinel 헤더를 설정하여 CDN 루프백에서 무한 루프를 사용하지 마십시오. - Cloud Manager 구성 파이프라인을 통해 업데이트된
cdn.yaml을(를) 배포합니다.
CDN 루프백에서 무한 루프 방지
AEM Edge 기능 이 CDN을 통해 소스에서 콘텐츠를 가져올 때 무한 루프가 발생할 수 있습니다. 이 가져오기는 CDN에 다시 들어가고, 동일한 원본 선택기 규칙과 일치하며, 함수로 다시 라우팅됩니다.
이를 방지하기 위해 sentinel(예: x-edgefunction-request) 헤더를 설정하여 원본 선택기 규칙에서 루프백 요청을 제외할 수 있습니다. 초기 방문자 요청에는 헤더가 없고 AEM Edge 함수에 도달합니다. 루프백 요청은 헤더를 운반하고 조건을 실패하며 대신 원본으로 라우팅됩니다.
다음 코드 및 구성 코드 조각은 CDN 루프백에서 무한 루프를 방지하는 방법을 보여 줍니다.
// src/index.js
addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));
...
// In the handler: set the sentinel on the loopback fetch
const loopbackRequest = new Request(`https://www.example.com${url.pathname}`, {
headers: { "x-edgefunction-request": "true" },
});
await fetch(loopbackRequest);
AEM Edge 함수 처리기에서 sentinel 헤더를 설정하는 방법은 AEM Edge 함수 예제를 참조하십시오.
# config/cdn.yaml (origin selector excerpt)
kind: "CDN"
version: "1"
data:
originSelectors:
rules:
- name: route-to-edge-function
when:
allOf:
...
- { reqHeader: x-edgefunction-request, exists: false } # skip loopback requests to prevent infinite loops
...
CDN 구성에서 이미 sentinel 헤더를 전달하는 요청을 제외하는 방법은 AEM Edge 함수 예제를 참조하십시오.
전체 예
AEM Edge 함수 예제 리포지토리에는 전체 config/cdn.yaml 규칙이 있는 인터셉터 함수가 포함되어 있습니다.