Skip to content

Instantly share code, notes, and snippets.

@cat5inthecradle
Last active January 10, 2022 17:14
Show Gist options
  • Select an option

  • Save cat5inthecradle/ecb94d418f7472679f0d14b77212a6bf to your computer and use it in GitHub Desktop.

Select an option

Save cat5inthecradle/ecb94d418f7472679f0d14b77212a6bf to your computer and use it in GitHub Desktop.
Redirect one domain to another via Cloudfront Lambda@Edge
AWSTemplateFormatVersion: 2010-09-09
Description: Cloudfront redirect lambda demo
Parameters:
FromDomain:
Type: String
Default: darin.dev-code.org
Description: The domain you wish to redirect traffic from
ToDomain:
Type: String
Default: code.org
Description: The domain you wish to redirect traffic to
HostedZoneId:
Type: String
Description: The HostedZoneId for the To/From Domains
RedirectType:
Type: String
Default: 302
AllowedValues:
- 301
- 302
Description: The redirect type, permanent or temporary
Resources:
PrimaryRecord:
Type: "AWS::Route53::RecordSet"
Properties:
HostedZoneId: !Ref HostedZoneId
Name: !Ref FromDomain
Type: A
AliasTarget:
HostedZoneId: Z2FDTNDATAQYW2
DNSName: !GetAtt CFDistribution.DomainName
CFDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Enabled: "true"
Comment: "Redirect www to root domain"
PriceClass: PriceClass_100
Aliases:
- !Ref FromDomain
DefaultCacheBehavior:
TargetOriginId: PrimaryOrigin
CachePolicyId: !Ref RedirectCachePolicy
LambdaFunctionAssociations:
- EventType: origin-request
LambdaFunctionARN: !Ref RedirectLambdaVersion4
ViewerProtocolPolicy: allow-all
ViewerCertificate:
AcmCertificateArn: !Ref Certificate
SslSupportMethod: sni-only
# The lambda prevents traffic from hitting this origin, but we need it regardless
Origins:
- Id: PrimaryOrigin
DomainName: !Ref FromDomain
CustomOriginConfig:
OriginProtocolPolicy: http-only
HTTPPort: 80
RedirectCachePolicy:
Type: AWS::CloudFront::CachePolicy
Properties:
CachePolicyConfig:
Name: RedirectCachePolicy
MinTTL: 3600
MaxTTL: 31536000
DefaultTTL: 86400
ParametersInCacheKeyAndForwardedToOrigin:
EnableAcceptEncodingGzip: false
CookiesConfig:
CookieBehavior: none
HeadersConfig:
HeaderBehavior: whitelist
Headers:
- Origin
QueryStringsConfig:
QueryStringBehavior: all
Certificate:
Type: AWS::CertificateManager::Certificate
Properties:
DomainName: !Ref FromDomain
ValidationMethod: DNS
DomainValidationOptions:
- DomainName: !Ref FromDomain
HostedZoneId: !Ref HostedZoneId
RedirectLambda:
Type: AWS::Lambda::Function
Properties:
Runtime: nodejs14.x
Role: !GetAtt RedirectLambdaRole.Arn
Handler: index.handler
Code:
ZipFile: !Sub |
'use strict';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const uri = request.uri;
const host = request.headers.host[0].value;
const querystring = request.querystring;
// Start building new url
let newUrl = '${ToDomain}';
// Append path
if (uri) newUrl += uri;
// Append query string
if (querystring && querystring != '') newUrl += "?" + querystring;
const response = {
status: '${RedirectType}',
statusDescription: '${RedirectType} Redirect to root domain',
headers: {
location: [{
key: 'Location',
value: newUrl
}]
}
};
callback(null, response);
};
Description: Redirect www traffic to root domain
TracingConfig:
Mode: Active
# To make a new version, bump the NAME of this resource and all references
RedirectLambdaVersion4:
Type: AWS::Lambda::Version
Properties:
FunctionName: !Ref RedirectLambda
RedirectLambdaRole:
Type: "AWS::IAM::Role"
Properties:
Path: "/"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: "AllowLambdaServiceToAssumeRole"
Effect: "Allow"
Action:
- "sts:AssumeRole"
Principal:
Service:
- "lambda.amazonaws.com"
- "edgelambda.amazonaws.com"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment