/Documentation

How to use same origin through AWS CloudFront

Updated Sep 14, 2026

Before you begin

Setup overview

Architecture Flow chart

CloudFront Function (Viewer Request)

Lambda@Edge (Origin Request)

Step 1. Create an origin in CloudFront

Step 2. Create a CloudFront Function

function handler(event) { var request = event.request; // Capture original viewer host if (request.headers.host) { request.headers['x-original-host'] = { value: request.headers.host.value }; } return request; }

Step 3. Create Lambda@Edge Function

export const handler = async (event) => { const request = event.Records[0].cf.request; const viewerIp = request.clientIp; // Read original viewer host captured by CloudFront Function let originalHost = request.headers['x-original-host']?.[0]?.value || ''; // Convert www.example.com → example.com originalHost = originalHost.replace(/^www\./i, ''); // Rewrite Host header to the Stape origin domain request.headers.host = [ { key: 'Host', value: request.origin.custom.domainName } ]; // Tell Stape traffic came through CloudFront request.headers['x-from-cdn'] = [ { key: 'X-From-CDN', value: 'cft-stape' } ]; // Pass real viewer IP request.headers['true-client-ip'] = [ { key: 'True-Client-IP', value: viewerIp } ]; // Pass original domain to custom header. This is only necessary if you are proxying requests to the standard Stape subdomain, rather than to your own connected subdomain. request.headers['x-stape-host'] = [ { key: 'X-Stape-Host', value: originalHost } ]; // Strip /metrics prefix if (request.uri.startsWith('/metrics')) { request.uri = request.uri.replace(/^\/metrics/, '') || '/'; } return request; };

Step 4. Configure the required CloudFront settings

AWS cloudfront behavior settings 1
AWS cloudfront behavior settings 2
AWS cloudfront behavior settings 3

Include Body

Origin Custom Headers

Testing and troubleshooting

Was this article helpful?

Comments

Can’t find what you are looking for?