Skip to content

Instantly share code, notes, and snippets.

@artyom
Created November 16, 2021 09:15
Show Gist options
  • Save artyom/7f8c35b54dac067d626596ea243911eb to your computer and use it in GitHub Desktop.
Save artyom/7f8c35b54dac067d626596ea243911eb to your computer and use it in GitHub Desktop.
CloudFormation example: adding custom HTTP headers to CloudFront distribution
Description: CloudFormation custom headers test
Resources:
SiteS3Bucket:
Type: AWS::S3::Bucket
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
SiteS3BucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref SiteS3Bucket
PolicyDocument:
Statement:
- Effect: Allow
Action: s3:GetObject
Principal:
AWS: !Sub 'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${CloudFrontOriginAccessIdentity}'
Resource:
- !Join
- /
- - !GetAtt SiteS3Bucket.Arn
- '*'
SiteCDN:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
CustomErrorResponses:
- ErrorCode: 403
ResponseCode: 404
ResponsePagePath: /err404.html
DefaultRootObject: index.html
Enabled: true
HttpVersion: http2
IPV6Enabled: true
PriceClass: PriceClass_100
Origins:
- Id: website-bucket
DomainName: !GetAtt SiteS3Bucket.RegionalDomainName
S3OriginConfig:
OriginAccessIdentity: !Sub "origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}"
DefaultCacheBehavior:
TargetOriginId: website-bucket
AllowedMethods: [GET, HEAD]
CachedMethods: [GET, HEAD]
Compress: true
ViewerProtocolPolicy: redirect-to-https
# https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6
# https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-origin-request-policies.html
OriginRequestPolicyId: acba4595-bd28-49b8-b9fe-13317c0390fa
# https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html#managed-response-headers-policies-security
ResponseHeadersPolicyId: 67f7725c-6f97-4210-82d7-5512b31e9d03
CloudFrontOriginAccessIdentity:
Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: CloudFront S3 Access
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment