Skip to content

Instantly share code, notes, and snippets.

@piotrekwitkowski
Last active February 14, 2024 22:38
Show Gist options
  • Save piotrekwitkowski/b5c5d6d7a0aa01813fdb936574e5fb0b to your computer and use it in GitHub Desktop.
Save piotrekwitkowski/b5c5d6d7a0aa01813fdb936574e5fb0b to your computer and use it in GitHub Desktop.
Redirect behavior for CloudFront with CDK and TypeScript
import { Stack } from "aws-cdk-lib";
import { BehaviorOptions, Function, FunctionCode, FunctionEventType } from "aws-cdk-lib/aws-cloudfront";
import { HttpOrigin } from "aws-cdk-lib/aws-cloudfront-origins";
import { join } from "path";
export const getRedirectBehavior = (scope: Stack, id: string, location: string): BehaviorOptions => {
const redirectFilePath = join(__dirname, 'redirect-function.js');
const redirectFunctionCode = FunctionCode.fromFile({ filePath: redirectFilePath });
const redirectFunction = new Function(scope, `${id}-default-redirect-function`, {
code: redirectFunctionCode
});
// this origin will never be actually used, but we need to specify it to satisfy CloudFront
const origin = new HttpOrigin(extractDomain(location));
return {
origin,
functionAssociations: [
{
eventType: FunctionEventType.VIEWER_REQUEST,
function: redirectFunction
}
]
};
}
const extractDomain = (url: string) => {
// 1. Remove protocol (https:// or http://)
url = url.replace(/(^\w+:\/\/)/i, "");
// 2. Remove path (everything after the slash
const slashIndex = url.indexOf("/");
if (slashIndex !== -1) {
url = url.substring(0, slashIndex);
}
return url;
}
function handler() {
var REDIRECT_URL = 'https://example.com/some-path';
return { statusCode: 301, headers: { location: { value: REDIRECT_URL } } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment