Static Website Architecture

·27 min read
Static Website Architecture

As mentioned in my welcome post, I’ve built plenty of websites over the years, most of them with a web server backed by a database. While looking for full-time work, I wanted a personal website – a single page with my details, credentials, and contact information. A web server with a database felt like overkill for that.

Then I found out that an indie game studio registered with an ABN also needs a web presence to justify the entitlement. And these days, a blog is trivially achievable with a static site generator such as the excellent Hugo.

So the requirement was simple: a static website, hosted cheaply, served over HTTPS, on a custom domain, reproducible from scratch. What followed was more complicated than I expected.

Why S3 alone isn’t enough

As cloud object storage, S3 is quite literally designed to serve files and data to client machines. While S3 can expose website endpoints, the addresses look like [bucket-name].s3-website.[region].amazonaws.com – not exactly professional-looking.

You’d think you could point a DNS record at that endpoint and be done. But if you want to serve content over HTTPS – like the vast majority of the internet – you need to issue an SSL certificate for your custom domain. Since S3 is object storage, it doesn’t natively support SSL certificates for custom domains.

To serve static content over HTTPS with a custom domain, you need CloudFront in front of the bucket. The AWS documentation covers steps up to exposing the website endpoint. At the other end of the scale, plenty of tutorials cover CloudFront-fronted static hosting, but they skip custom domains or hand-wave the resource creation with console clicks.

I also wanted a GitHub Actions pipeline that could recreate the entire architecture from scratch at any time. Some posts got me part of the way there, but nothing was comprehensive, so I pulled the pieces together – and hit a few gotchas along the way.

What this post covers

This is part one of a series. This post deals with the AWS resources:

  • The resources – website bucket, logging buckets, Route 53 records, certificate, CloudFront distribution and its access controls
  • Deployment – a GitHub Actions workflow deploying via CloudFormation using OIDC
  • IAM policy – the least-privilege policy that makes it all work
  • Deployment – using GitHub Actions to deploy the stack and website content
  • References – the sources that saved me hours
  • Final template – the complete, copy-pasteable CloudFormation

The website resources

These are the AWS resources used to host the website:

Website S3 bucket

The AWS::S3::Bucket resource hosts the static content and serves the website’s files directly:

WebsiteBucket:
  Type: AWS::S3::Bucket
  DeletionPolicy: Delete
  Properties:
    BucketName: !Ref WebsiteDomain
    PublicAccessBlockConfiguration:
      RestrictPublicBuckets: true
      IgnorePublicAcls: true
      BlockPublicPolicy: true
      BlockPublicAcls: true
    LoggingConfiguration:
      DestinationBucketName: !Ref WebsiteRequestLoggingBucket
      TargetObjectKeyFormat:
        PartitionedPrefix:
          PartitionDateSource: EventTime

Three decisions worth explaining:

Delete by default - because the website content lives in a Git repository, DeletionPolicy: Delete is safe: deleting the stack removes the bucket, and the content can always be redeployed.

Block all public access - RestrictPublicBuckets, IgnorePublicAcls, BlockPublicPolicy and BlockPublicAcls are all set to true. The content will be served exclusively via CloudFront, so there’s no reason for the bucket to ever be publicly reachable.

Server access logging - a LoggingConfiguration sends request logs to the separate bucket defined below. PartitionedPrefix writes them into one folder per day (<account>/<region>/<bucket>/yyyy/MM/dd/) instead of a single flat prefix, filed by the day the requests happened (EventTime), so Athena can read just the days a query asks for - see part two.

There’s deliberately no WebsiteConfiguration. That setting turns on S3’s website endpoint, which this setup never uses: CloudFront reads the bucket through its regular endpoint using origin access control, and serves the homepage through its own DefaultRootObject (covered in the CloudFront distribution section).

Website S3 bucket policy

Since public access is blocked, CloudFront needs explicit permission. An AWS::S3::BucketPolicy grants the CloudFront service principal read access to the bucket:

  WebsiteBucketPolicy:
    Type: AWS::S3::BucketPolicy
    DeletionPolicy: Delete
    Properties:
      Bucket: !Ref WebsiteBucket
      PolicyDocument:
        Version: 2012-10-17
        Id: PolicyForCloudFrontPrivateContent
        Statement:
          - Action: s3:GetObject
            Sid: AllowCloudFrontServicePrincipal
            Effect: Allow
            Principal:
              Service: cloudfront.amazonaws.com
            Resource: !Sub arn:${AWS::Partition}:s3:::${WebsiteBucket}/*
            Condition:
              StringEquals:
                'AWS:SourceArn': !Sub arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}
          - Action: 's3:*'
            Sid: DenyInsecureTransport
            Effect: Deny
            Principal: '*'
            Resource:
              - !Sub arn:${AWS::Partition}:s3:::${WebsiteBucket}
              - !Sub arn:${AWS::Partition}:s3:::${WebsiteBucket}/*
            Condition:
              Bool:
                'aws:SecureTransport': 'false'

The Condition is the important part: it pins the permission to a specific distribution ARN, so no other CloudFront distribution - yours or anyone else’s - can read from the bucket.

The second statement denies every request to the bucket that doesn’t arrive over HTTPS, whoever makes it. CloudFront already reaches S3 over HTTPS (it matches the viewer’s protocol, and viewers are redirected to HTTPS first), so this only stops plain-HTTP calls to the bucket directly.

Website request logging S3 bucket

The bucket above needs somewhere to send its logs. This second bucket collects them:

Parameters:
  LogRetentionDays:
    Description: >-
      Days to keep S3 and CloudFront request logs (queried with Athena via
      deploy/infra-monitoring.yml) before they're deleted
    Type: Number
    Default: 365
    MinValue: 1

Resources:
  WebsiteRequestLoggingBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      BucketName: !Sub ${WebsiteDomain}-bucket-requests
      PublicAccessBlockConfiguration:
        RestrictPublicBuckets: true
        IgnorePublicAcls: true
        BlockPublicPolicy: true
        BlockPublicAcls: true
      LifecycleConfiguration:
        Rules:
          - Status: Enabled
            Id: Expire old logs
            ExpirationInDays: !Ref LogRetentionDays

Retain, always - unlike the content bucket, the logging buckets use DeletionPolicy: Retain and UpdateReplacePolicy: Retain. Logs are historical data; losing them because a stack was deleted would be a bad trade.

Expire old logs - the lifecycle configuration deletes log files once they’re LogRetentionDays old (a year by default), so the bucket doesn’t grow forever. I originally tiered logs down to Standard Infrequent Access after 30 days and Glacier Instant Retrieval after 90 instead, but S3 doesn’t transition objects smaller than 128 KB into those storage classes, and a log file is a few KB. The transitions almost never happened, and the logs just piled up.

Website request logging bucket policy

S3 server access logging needs explicit permission to write:

  WebsiteRequestLoggingBucketPolicy:
    Type: AWS::S3::BucketPolicy
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      Bucket: !Ref WebsiteRequestLoggingBucket
      PolicyDocument:
        Version: 2012-10-17
        Id: PolicyForBucketRequestLogging
        Statement:
          - Action: s3:PutObject
            Sid: AllowS3LoggingServicePrincipal
            Effect: Allow
            Principal:
              Service: logging.s3.amazonaws.com
            Resource: !Sub arn:${AWS::Partition}:s3:::${WebsiteRequestLoggingBucket}/*
            Condition:
              StringEquals:
                aws:SourceAccount: !Ref AWS::AccountId

The aws:SourceAccount condition means only your own account’s logging service can write here – nobody else can point their bucket logs at it.

Route 53 record set group

My first instinct was to have CloudFormation create the Route 53 hosted zone. Since I’d already registered the domain, surely that would be straightforward?

Not quite. The hosted zone also holds NS, MX, TXT, SPF, DKIM and DMARC records, plus CNAME validation records I didn’t want to disturb. Instead, I created the hosted zone up front, passed its ID as a parameter, and used it only for the website’s alias records:

Parameters:
  WebsiteHostedZoneId:
    Description: Hosted Zone ID for DNS record creation
    Type: String

Resources:
  WebsiteRecordSet:
    Type: AWS::Route53::RecordSetGroup
    DeletionPolicy: Delete
    Properties:
      HostedZoneId: !Ref WebsiteHostedZoneId
      RecordSets:
        - Name: !Ref WebsiteDomain
          Type: A
          AliasTarget:
            DNSName: !GetAtt CloudFrontDistribution.DomainName
            HostedZoneId: Z2FDTNDATAQYW2
        - Name: !Sub www.${WebsiteDomain}
          Type: A
          AliasTarget:
            DNSName: !GetAtt CloudFrontDistribution.DomainName
            HostedZoneId: Z2FDTNDATAQYW2
        - Name: !Ref WebsiteDomain
          Type: AAAA
          AliasTarget:
            DNSName: !GetAtt CloudFrontDistribution.DomainName
            HostedZoneId: Z2FDTNDATAQYW2
        - Name: !Sub www.${WebsiteDomain}
          Type: AAAA
          AliasTarget:
            DNSName: !GetAtt CloudFrontDistribution.DomainName
            HostedZoneId: Z2FDTNDATAQYW2

The A records answer IPv4 lookups and the AAAA records IPv6 ones; the AAAA pair only does anything because the distribution has IPv6 turned on (see below). Without them, IPv6-only clients can’t reach the site even though CloudFront would serve them.

The first gotcha: that mysterious hardcoded Z2FDTNDATAQYW2. The AWS documentation states:

“When you create alias resource record sets, you must specify Z2FDTNDATAQYW2 for the HostedZoneId property. Alias resource record sets for CloudFront can’t be created in a private zone.”

That’s CloudFront’s own hosted zone ID – a constant for every CloudFront distribution, not the hosted zone your records live in. This took a fair amount of head-scratching to discover.

CloudFront distribution

Before committing anything to CloudFormation, I first created the distribution through the AWS Console to prove the configuration worked, then translated the settings into the template.

  CloudFrontDistribution:
    Type: AWS::CloudFront::Distribution
    DeletionPolicy: Delete
    Properties:
      DistributionConfig:
        Aliases:
          - !Ref WebsiteDomain
          - !Sub www.${WebsiteDomain}
        DefaultRootObject: index.html
        HttpVersion: http2and3
        IPV6Enabled: true
        Origins:
          - Id: !GetAtt WebsiteBucket.RegionalDomainName
            DomainName: !GetAtt WebsiteBucket.RegionalDomainName
            S3OriginConfig:
              OriginAccessIdentity: ''
            OriginAccessControlId: !GetAtt CloudFrontOriginAccessControl.Id
        Enabled: true
        DefaultCacheBehavior:
          TargetOriginId: !GetAtt WebsiteBucket.RegionalDomainName
          AllowedMethods:
            - GET
            - HEAD
          Compress: true
          ViewerProtocolPolicy: redirect-to-https
          CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6
          ResponseHeadersPolicyId: !Ref SecurityHeadersPolicy
          FunctionAssociations:
            - EventType: viewer-request
              FunctionARN: !GetAtt CloudFrontRewritePrettyUrlFunction.FunctionARN
        CustomErrorResponses:
          - ErrorCode: 403
            ResponseCode: 404
            ResponsePagePath: /404.html
            ErrorCachingMinTTL: 60
          - ErrorCode: 404
            ResponseCode: 404
            ResponsePagePath: /404.html
            ErrorCachingMinTTL: 60
        ViewerCertificate:
          AcmCertificateArn: !Ref WebsiteCertificate
          MinimumProtocolVersion: TLSv1.2_2021
          SslSupportMethod: sni-only

Aliases – both the apex domain and www. are listed, so both serve the site, although the CloudFront function redirects www. to the apex.

HTTP/3 and IPv6 - HttpVersion: http2and3 lets browsers use HTTP/3 over QUIC where they support it, falling back to HTTP/2, and IPV6Enabled gives the distribution IPv6 addresses for the AAAA records to point at. Neither costs anything extra.

DefaultRootObject - index.html loads without the file being specified in the URL.

Origins – CloudFront supports multiple origins, but here there’s one: the S3 bucket. The origin uses the bucket’s regional domain name as both its Id and DomainName.

HTTPS everywhere - ViewerProtocolPolicy: redirect-to-https sends plain HTTP requests to their HTTPS equivalents, and ViewerCertificate pins the distribution to the ACM certificate (covered below), TLS 1.2 as a floor, with SNI-only support.

Two settings in the origin config deserve explanation – and one important distinction tripped me up early on: origin access control (OAC) versus origin access identity (OAI). These are two generations of the same idea: restricting an S3 origin so only your CloudFront distribution can read from it.

OAI is the original mechanism – a special CloudFront identity attached to the distribution and granted access via the bucket policy. OAC is its successor: the distribution cryptographically signs every origin request with SigV4, and the bucket policy trusts requests signed for that specific distribution. OAC adds features OAI lacks – support for SSE-KMS encrypted buckets among them.

OAC is the recommended approach today, so that’s what I used. Which leaves the oddity in the snippet above: an empty OriginAccessIdentity alongside the OriginAccessControlId. Per the AWS documentation: “If you’re using origin access control (OAC) instead of origin access identity, specify an empty OriginAccessIdentity element.”

Finally, the DefaultCacheBehavior limits methods to GET and HEAD, enables Compress - a no-brainer for text-heavy pages - and, rather than defining a custom caching policy from scratch, references AWS’s managed CachingOptimized policy by its GUID: 658327ea-f89d-4fab-a63d-7e88639e58f6. It also attaches the response headers policy and runs the CloudFront function on every viewer request, both covered below.

Custom error responses - with origin access control, S3 answers a request for a missing file with 403 Forbidden rather than 404 Not Found, because CloudFront isn’t allowed to list the bucket and so can’t be told the key doesn’t exist. CustomErrorResponses turns both into a 404 and serves Hugo’s 404.html page, caching the error for a minute.

CloudFront function

A CloudFront function runs at the edge on every viewer request, before CloudFront checks its cache. A cache behaviour can have only one viewer-request function, so this one does three jobs:

  CloudFrontRewritePrettyUrlFunction:
    Type: AWS::CloudFront::Function
    Properties:
      AutoPublish: true
      Name: maceage-blog-rewrite-pretty-urls
      FunctionConfig:
        Comment: 404 vulnerability probes; redirect www to the bare domain; enable pretty URLs for Hugo
        Runtime: cloudfront-js-2.0
      FunctionCode: |
        var PROBE = /\.php$|\.php\/|\/(wp-|\.env|\.git)/i;

        function queryString(qs) {
            var parts = [];
            for (var key in qs) {
                var values = qs[key].multiValue || [qs[key]];
                for (var i = 0; i < values.length; i++) {
                    parts.push(values[i].value === '' ? key : key + '=' + values[i].value);
                }
            }
            return parts.length ? '?' + parts.join('&') : '';
        }

        function handler(event) {
            var request = event.request;
            if (PROBE.test(request.uri)) {
                return {
                    statusCode: 404,
                    statusDescription: 'Not Found',
                    headers: {
                        'content-type': { value: 'text/plain' },
                        'cache-control': { value: 'public, max-age=86400' },
                        'x-content-type-options': { value: 'nosniff' }
                    },
                    body: { encoding: 'text', data: 'Not Found' }
                };
            }
            var host = request.headers.host ? request.headers.host.value : '';
            if (host.startsWith('www.')) {
                return {
                    statusCode: 301,
                    statusDescription: 'Moved Permanently',
                    headers: {
                        location: { value: 'https://' + host.slice(4) + request.uri + queryString(request.querystring) }
                    }
                };
            }
            var uri = request.uri;
            if (uri.endsWith('/')) {
                request.uri += 'index.html';
            } else if (!uri.slice(uri.lastIndexOf('/') + 1).includes('.')) {
                request.uri += '/index.html';
            }
            return request;
        }

Pretty URLs - Hugo publishes each page as index.html in its own folder and links to the folder, like /posts/foo/. DefaultRootObject only applies to the root of the site, so without help a request for /posts/foo/ asks S3 for a key that doesn’t exist. The function appends index.html to any URI ending in /, and /index.html to any whose last segment has no file extension.

www to the apex - a request to www. gets a 301 to the same path and query on the bare domain, so search engines index one copy of the site rather than two.

Vulnerability probes - scanners constantly request .php files, WordPress paths and .env or .git files. None exist here, so the function answers them with a plain 404 at the edge instead of passing them on to S3.

CloudFront response headers policy

A response headers policy adds headers to every response CloudFront sends. AWS’s managed SecurityHeadersPolicy covers the usual security headers but can’t be extended, so the template defines its own with the same headers plus two more. A parameter and a condition decide whether CSP violation reports are sent anywhere:

Parameters:
  CspReportUrl:
    Description: >-
      URL browsers send CSP violation reports to (the ReportUrl output of
      deploy/infra-csp-reports.yml). Leave empty to send no reports.
    Type: String
    Default: ""

Conditions:
  HasCspReportUrl: !Not [!Equals [!Ref CspReportUrl, ""]]

Resources:
  SecurityHeadersPolicy:
    Type: AWS::CloudFront::ResponseHeadersPolicy
    DeletionPolicy: Delete
    Properties:
      ResponseHeadersPolicyConfig:
        Name: !Sub ${WebsiteName}-security-headers
        Comment: Security headers, Permissions-Policy and a report-only Content-Security-Policy
        SecurityHeadersConfig:
          StrictTransportSecurity:
            AccessControlMaxAgeSec: 31536000
            Override: true
          ContentTypeOptions:
            Override: true
          FrameOptions:
            FrameOption: SAMEORIGIN
            Override: true
          ReferrerPolicy:
            ReferrerPolicy: strict-origin-when-cross-origin
            Override: true
          XSSProtection:
            Protection: false
            Override: true
        CustomHeadersConfig:
          Items:
            - Header: Permissions-Policy
              Override: true
              Value: >-
                camera=(), microphone=(), geolocation=(), payment=(),
                usb=(), serial=(), hid=(), midi=(), display-capture=(),
                browsing-topics=()
            - Header: Content-Security-Policy-Report-Only
              Override: true
              Value: !Join
                - ''
                - - >-
                    default-src 'self';
                    script-src 'self'
                    'sha256-39Zqt7USDaKXYnyFu43RoKSaKWOukkNxpUw+uK+NolQ='
                    'sha256-KfEK7rkBBc+JXGcAvP13f629b+LMq94vut2Uzu4v7NU='
                    'sha256-ZdU3LCEvugLQ+xTzltOgd1BRUKNZnVO6fzY80brkXXQ='
                    https://www.googletagmanager.com https://gc.zgo.at;
                    style-src 'self' 'unsafe-inline';
                    img-src 'self' data: https://*.google-analytics.com https://*.googletagmanager.com https://*.google.com https://*.g.doubleclick.net https://maceage.goatcounter.com;
                    connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com https://*.google.com https://*.g.doubleclick.net https://maceage.goatcounter.com;
                    font-src 'self';
                    frame-src https://www.youtube.com https://www.youtube-nocookie.com;
                    object-src 'none';
                    base-uri 'self';
                    form-action 'self';
                    frame-ancestors 'self'
                  - !If
                    - HasCspReportUrl
                    - !Sub '; report-uri ${CspReportUrl}; report-to csp'
                    - ''
            - !If
              - HasCspReportUrl
              - Header: Reporting-Endpoints
                Override: true
                Value: !Sub 'csp="${CspReportUrl}"'
              - !Ref AWS::NoValue

The managed headers, mostly - HSTS for a year, X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN and Referrer-Policy: strict-origin-when-cross-origin keep the managed policy’s values. The exception is X-XSS-Protection, sent as 0: the old browser XSS filters it controls could be abused to block or leak parts of a page, and the CSP is the real defence.

Permissions-Policy - turns off browser features the blog never uses, such as the camera, microphone and location, while leaving the ones YouTube embeds and the code blocks’ Copy button need.

Report-only Content-Security-Policy - lists where scripts, styles, images and frames may come from. The blog’s own inline scripts are allowed by their SHA-256 hashes, so any change to them needs a new hash. As Content-Security-Policy-Report-Only, browsers block nothing and only report what would have been blocked; renaming the header to Content-Security-Policy enforces it once the reports stay clean.

Optional reporting - when CspReportUrl is set, the HasCspReportUrl condition adds report-uri and report-to to the policy and a Reporting-Endpoints header naming the endpoint, so browsers POST each violation there. Left empty, AWS::NoValue drops the header entirely and violations only appear in the browser console.

CloudFront origin access control

The distribution references an origin access control, so one must be created:

  CloudFrontOriginAccessControl:
    Type: AWS::CloudFront::OriginAccessControl
    DeletionPolicy: Delete
    Properties:
      OriginAccessControlConfig:
        Name: !GetAtt WebsiteBucket.RegionalDomainName
        OriginAccessControlOriginType: s3
        SigningBehavior: always
        SigningProtocol: sigv4

SigningBehavior: always ensures CloudFront signs every origin request – including those for cached content – with SigV4, the only valid value for SigningProtocol.

CloudFront request logging bucket

CloudFront can also log detailed information about every viewer request, so it gets its own log bucket:

  CloudFrontRequestLoggingBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      BucketName: !Sub ${WebsiteDomain}-cloudfront-requests
      PublicAccessBlockConfiguration:
        RestrictPublicBuckets: true
        IgnorePublicAcls: true
        BlockPublicPolicy: true
        BlockPublicAcls: true
      LifecycleConfiguration:
        Rules:
          - Status: Enabled
            Id: Expire old logs
            ExpirationInDays: !Ref LogRetentionDays
      OwnershipControls:
        Rules:
          - ObjectOwnership: BucketOwnerPreferred

Same shape as the request-logging bucket: public access blocked, logs expired after LogRetentionDays, and retained on deletion or replacement.

One more gotcha lurked here. Without the OwnershipControls block, deployment fails with “The S3 Bucket that you specified for CloudFront logs does not enable ACL access” - which prevents CloudFront from writing logs entirely. Setting ObjectOwnership: BucketOwnerPreferred allows the log delivery service’s ACL headers to do their job.

CloudFront request logging bucket policy

As with S3 logging, CloudFront log delivery needs explicit permission - this time via the delivery.logs.amazonaws.com service principal:

  CloudFrontRequestLoggingBucketPolicy:
    Type: AWS::S3::BucketPolicy
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      Bucket: !Ref CloudFrontRequestLoggingBucket
      PolicyDocument:
        Version: 2012-10-17
        Id: PolicyForCloudFrontRequestLogging
        Statement:
          - Action: s3:PutObject
            Sid: AllowLogDeliveryServicePrincipal
            Effect: Allow
            Principal:
              Service: delivery.logs.amazonaws.com
            Resource: !Sub arn:${AWS::Partition}:s3:::${CloudFrontRequestLoggingBucket}/AWSLogs/${AWS::AccountId}/CloudFront/*
            Condition:
              StringEquals:
                s3:x-amz-acl: bucket-owner-full-control
                aws:SourceAccount: !Ref AWS::AccountId
              ArnLike:
                aws:SourceArn: !Sub arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:delivery-source:CreatedByCloudFront-${CloudFrontDistribution.Id}

This is the most paranoid policy in the stack, with three conditions stacked up:

Account-scoped - aws:SourceAccount restricts writes to your own account.

ACL-verified - the s3:x-amz-acl: bucket-owner-full-control header forces ownership transfer. Without it, log objects delivered from another account would remain owned by the uploader – and given the bucket blocks public access, you wouldn’t be able to read, modify, or delete them.

Source-verified - the ArnLike condition on aws:SourceArn accepts deliveries originating only from this specific CloudFront distribution.

CloudFront access logs delivery

CloudFront v2 logging uses vended log delivery, which requires three resources – a delivery source, a destination, and a delivery binding them together.

Delivery source – identifies where the logs come from:

  CloudFrontAccessLogsDeliverySource:
    Type: AWS::Logs::DeliverySource
    DeletionPolicy: Delete
    Properties:
      LogType: ACCESS_LOGS
      Name: !Sub ${WebsiteName}-cloudfront-log-delivery-source
      ResourceArn: !Sub
        - arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:distribution/${Distribution}
        - Distribution: !GetAtt CloudFrontDistribution.Id

Delivery - binds the source to the destination:

  CloudFrontAccessLogsDelivery:
    Type: AWS::Logs::Delivery
    DeletionPolicy: Delete
    DependsOn: CloudFrontAccessLogsDeliverySource
    Properties:
      DeliveryDestinationArn: !GetAtt CloudFrontAccessLogsDeliveryDestination.Arn
      DeliverySourceName: !Sub ${WebsiteName}-cloudfront-log-delivery-source
      RecordFields:
        - date
        - time
        - x-edge-location
        - sc-bytes
        - c-ip
        - cs-method
        - 'cs(Host)'
        - cs-uri-stem
        - sc-status
        - 'cs(Referer)'
        - 'cs(User-Agent)'
        - cs-uri-query
        - x-edge-result-type
        - x-edge-request-id
        - x-host-header
        - cs-protocol
        - cs-bytes
        - time-taken
        - x-forwarded-for
        - ssl-protocol
        - ssl-cipher
        - x-edge-response-result-type
        - cs-protocol-version
        - fle-status
        - fle-encrypted-fields
        - c-port
        - time-to-first-byte
        - x-edge-detailed-result-type
        - sc-content-type
        - sc-content-len
        - sc-range-start
        - sc-range-end
        - c-country
        - asn
        - origin-fbl
        - origin-lbl
        - 'timestamp(ms)'
      S3SuffixPath: AWSLogs/{account-id}/CloudFront/{yyyy}/{MM}/{dd}/

S3SuffixPath delivers each log into a folder for its day, for the same reason as the S3 access logs above.

RecordFields picks the fields each log record carries. Leaving it out gets CloudFront’s default set, the fields of its legacy log format; listing them adds five more on top: the viewer’s country (c-country) and network (asn), how long the origin took to send the first and last byte of its response (origin-fbl, origin-lbl), and the request time to the millisecond (timestamp(ms)). The list replaces the default set rather than adding to it, so it repeats the default fields too, all but one: cs(Cookie), the cookies each viewer sent. The site sets none of its own, so that field would only record Google Analytics’ visitor IDs next to each IP address for as long as the logs are kept.

Delivery destination – where the logs land, as an S3 bucket in JSON format:

  CloudFrontAccessLogsDeliveryDestination:
    Type: AWS::Logs::DeliveryDestination
    DeletionPolicy: Delete
    Properties:
      DestinationResourceArn: !GetAtt CloudFrontRequestLoggingBucket.Arn
      Name: !Sub ${WebsiteName}-cloudfront-log-delivery-destination
      OutputFormat: json

CloudFront has two logging modes: legacy and v2. Legacy is still the default when provisioning with CloudFormation, and it’s easy to end up with it by accident. The three resources above are what route you onto v2 logging instead - delivering structured JSON rather than the legacy gzipped CSV format.

ACM website certificate

The final piece of the puzzle: the SSL certificate that lets CloudFront serve the site over HTTPS:

WebsiteCertificate:
  Type: AWS::CertificateManager::Certificate
  DeletionPolicy: Delete
  Properties:
    DomainName: !Ref WebsiteDomain
    SubjectAlternativeNames:
      - !Sub www.${WebsiteDomain}
    DomainValidationOptions:
      - DomainName: !Sub ${WebsiteDomain}
        HostedZoneId: !Ref WebsiteHostedZoneId
    ValidationMethod: DNS

A SubjectAlternativeName covers the www. subdomain so both addresses are valid.

Deployment

I chose GitHub Actions over CodeBuild for deployment.

No extra infrastructure to manage – CodeBuild is a separate build environment to configure and monitor; GitHub Actions just runs.

Everything in one place – no switching between AWS Console and CI to check on the build; it’s all in the GitHub interface next to the code.

Deployment prerequisites

Before deploying the CloudFormation template, these steps are required:

  1. Create the hosted zone for the DNS records
  2. Point the registered domain’s name servers at the hosted zone
  3. Pass the hosted zone ID as the WebsiteHostedZoneId parameter
  4. Run the CloudFormation template
  5. Confirm the creation of the DNS CNAME records for the website certificate

Step 5 matters most, because DNS validation requires a manual step. In the AWS Console, the certificate sits in Pending validation until the CNAME records exist – and the build won’t proceed without it. It’s a one-time setup; the records can be reused for future deployments.

Deploying with GitHub Actions

Deployment itself was straightforward. The interesting part was the trust relationship between GitHub and AWS.

OpenID Connect (OIDC) – rather than storing long-lived AWS access keys as GitHub secrets, the workflow assumes an IAM role using OIDC, following the steps in the GitHub documentation.

Effectively: register token.actions.githubusercontent.com as an identity provider in the AWS Console, then grant the deployment role permission to be assumed from your repository via a trust policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::[AccountID]:oidc-provider/token.actions.githubusercontent.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:[Organisation]/[Repository]:environment:[Environment]"
        }
      }
    }
  ]
}

The Condition in particular is worth emphasising: it scopes the trust to a single repository, and within it to one GitHub environment. This is what makes it possible to run CloudFormation in CI without long-lived credentials. GitHub’s own examples often use repo:[Organisation]/[Repository]:*, but that wildcard lets a workflow on any branch assume the role, including a branch whose workflow file was edited to do something else.

A job that names an environment (environment: blog) presents environment:blog as its subject instead of the branch, so the role can be assumed only by jobs deploying to that environment. Each deploy role gets its own environment, so a job can’t assume another stack’s role. The environment’s deployment branches setting is limited to main, and GitHub refuses to run a job for that environment from any other branch, so the branch restriction still holds: it moves from the trust policy to the environment. Environments also give each deploy a history in the repository’s Deployments page, and can hold the role ARN as an environment secret or require a reviewer. If the repository uses immutable subject claims, the subject includes the owner and repository IDs (repo:[Organisation]@[OwnerID]/[Repository]@[RepoID]:environment:[Environment]); CloudTrail’s AssumeRoleWithWebIdentity events show the exact value a run presents.

GitHub Actions Workflow

The workflow has six steps:

  1. Clone repository - actions/checkout
  2. Configure AWS credentials – assume the role via aws-actions/configure-aws-credentials
  3. Deploy CloudFormation stack - aws-actions/aws-cloudformation-github-deploy
  4. Sync files to the website S3 bucket - aws s3 sync
  5. Get CloudFront distribution ID - via aws cloudformation describe-stacks
  6. Invalidate CloudFront distribution - aws cloudfront create-invalidation to clear the caches
name: Deploy Website

on:
  push:
    branches:
      - master

env:
  AWS_REGION: "us-east-1"
  WEBSITE_NAME: "maceage"
  WEBSITE_DOMAIN: "maceage.com"

permissions:
  id-token: write
  contents: read

jobs:
  DeployWebsite:
    runs-on: ubuntu-latest
    environment: website
    steps:
      - name: Clone repository
        uses: actions/checkout@v7

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ secrets.IAM_ROLE_ARN }}
          role-session-name: MaceageWebsiteDeployment
          aws-region: ${{ env.AWS_REGION }}

      - name: Deploy CloudFormation Stack
        uses: aws-actions/aws-cloudformation-github-deploy@v2
        with:
          name: MaceageWebsite
          template: deploy/infra-website.yml
          parameter-overrides: "WebsiteName=${{ env.WEBSITE_NAME }},WebsiteDomain=${{ env.WEBSITE_DOMAIN }},WebsiteHostedZoneId=${{ secrets.WEBSITE_HOSTED_ZONE_ID }}"

      - name: Sync website files to S3 Bucket
        run: |
          aws s3 sync src/ s3://${{ env.WEBSITE_DOMAIN }} --exact-timestamps --delete

      - name: Get CloudFront distribution ID
        run: |
          echo "DISTRIBUTION_ID=$(aws cloudformation --region us-east-1 describe-stacks --stack-name MaceageWebsite --query 'Stacks[0].Outputs[?OutputKey==`CloudFrontDistributionId`].OutputValue' --output text)" >> $GITHUB_ENV

      - name: Invalidate CloudFront distribution
        run: |
          aws cloudfront create-invalidation --distribution-id ${{ env.DISTRIBUTION_ID }} --paths '/*'

IAM policy

Getting the IAM policy right was pure trial and error – deploy, watch it fail, add the missing permission, repeat.

The eventual result:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "ManageCertificate",
            "Effect": "Allow",
            "Action": [
                "acm:DeleteCertificate",
                "acm:DescribeCertificate",
                "acm:RequestCertificate"
            ],
            "Resource": "*"
        },
        {
            "Sid": "ManageCloudFormationStacks",
            "Effect": "Allow",
            "Action": [
                "cloudformation:CreateStack",
                "cloudformation:DescribeEvents",
                "cloudformation:CreateChangeSet",
                "cloudformation:DescribeChangeSet",
                "cloudformation:ExecuteChangeSet",
                "cloudformation:DeleteChangeSet",
                "cloudformation:DescribeStacks"
            ],
            "Resource": "*"
        },
        {
            "Sid": "ManageCloudFront",
            "Effect": "Allow",
            "Action": [
                "cloudfront:CreateOriginAccessControl",
                "cloudfront:GetFunction",
                "cloudfront:ListFunctions",
                "cloudfront:PublishFunction",
                "cloudfront:DeleteOriginAccessControl",
                "cloudfront:TagResource",
                "cloudfront:AllowVendedLogDeliveryForResource",
                "cloudfront:CreateDistribution",
                "cloudfront:CreateFunction",
                "cloudfront:CreateInvalidation",
                "cloudfront:GetDistribution",
                "cloudfront:DescribeFunction",
                "cloudfront:ListTagsForResource",
                "cloudfront:GetOriginAccessControl",
                "cloudfront:UpdateFunction",
                "cloudfront:UpdateDistribution",
                "cloudfront:DeleteDistribution",
                "cloudfront:DeleteFunction",
                "cloudfront:CreateResponseHeadersPolicy",
                "cloudfront:GetResponseHeadersPolicy",
                "cloudfront:UpdateResponseHeadersPolicy",
                "cloudfront:DeleteResponseHeadersPolicy",
                "cloudfront:ListResponseHeadersPolicies"
            ],
            "Resource": "*"
        },
        {
            "Sid": "ManageLogs",
            "Effect": "Allow",
            "Action": [
                "logs:GetDelivery",
                "logs:DeleteDeliverySource",
                "logs:GetDeliveryDestinationPolicy",
                "logs:DescribeDeliverySources",
                "logs:CreateDelivery",
                "logs:GetDeliveryDestination",
                "logs:GetLogDelivery",
                "logs:PutDeliverySource",
                "logs:ListTagsForResource",
                "logs:DeleteDeliveryDestinationPolicy",
                "logs:DescribeDeliveryDestinations",
                "logs:CreateLogDelivery",
                "logs:GetDeliverySource",
                "logs:PutDeliveryDestination",
                "logs:UpdateLogDelivery",
                "logs:UpdateDeliveryConfiguration",
                "logs:DeleteLogDelivery",
                "logs:PutDeliveryDestinationPolicy",
                "logs:DescribeDeliveries",
                "logs:DeleteDeliveryDestination",
                "logs:DeleteDelivery"
            ],
            "Resource": "*"
        },
        {
            "Sid": "ModifyRecords",
            "Effect": "Allow",
            "Action": [
                "route53:GetChange",
                "route53:GetHostedZone",
                "route53:ChangeResourceRecordSets",
                "route53:ListResourceRecordSets",
                "route53:DeleteHostedZone",
                "route53:ListTagsForResource",
                "route53:ListQueryLoggingConfigs"
            ],
            "Resource": "*"
        },
        {
            "Sid": "ManageBuckets",
            "Effect": "Allow",
            "Action": [
                "s3:CreateBucket",
                "s3:ListBucket",
                "s3:DeleteBucket",
                "s3:PutBucketPublicAccessBlock",
                "s3:PutBucketOwnershipControls",
                "s3:GetBucketAcl",
                "s3:DeleteBucketPolicy",
                "s3:GetBucketPolicy",
                "s3:PutBucketWebsite",
                "s3:PutBucketLogging",
                "s3:PutLifecycleConfiguration",
                "s3:PutBucketAcl",
                "s3:PutBucketPolicy",
                "s3:DeleteBucketWebsite"
            ],
            "Resource": "*"
        },
        {
            "Sid": "DeployArtifacts",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:DeleteObject",
                "s3:PutObjectAcl"
            ],
            "Resource": [
                "arn:aws:s3:::blog.maceage.com/*",
                "arn:aws:s3:::blog.maceage.com-bucket-requests/*",
                "arn:aws:s3:::blog.maceage.com-cloudfront-requests/*"
            ]
        },
        {
            "Sid": "PublishDeployHeartbeat",
            "Effect": "Allow",
            "Action": "cloudwatch:PutMetricData",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "cloudwatch:namespace": "MaceageBlog"
                }
            }
        },
        {
            "Sid": "ReadBookmarkCovers",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::blog.maceage.com-raindrop/*"
        },
        {
            "Sid": "QueryBookmarkTable",
            "Effect": "Allow",
            "Action": [
                "dynamodb:Query"
            ],
            "Resource": "arn:aws:dynamodb:us-east-1:[AccountID]:table/maceage-blog-raindrops"
        }
    ]
}

Given the breadth of resources this stack creates, a broad Resource: "*" is unavoidable – many of these services don’t support resource-level permissions on the resources being created.

The last two statements aren’t for the stack at all: the same deployment builds the blog’s bookmark pages, reading bookmarks from DynamoDB and their cover images from S3 - see Adding Bookmarks to My Blog Part 2.

References

Three discoveries shaped the final architecture:

Deploy outside us-east-1 - “To use an ACM certificate with CloudFront, make sure you request (or import) the certificate in the US East (N. Virginia) Region (us-east-1).” I initially created the S3 bucket and distribution in ap-southeast-2 - but CloudFront distributions must live in us-east-1 to use ACM certificates, so I placed everything in us-east-1 rather than fighting cross-region with custom resources. There’s a relevant GitHub issue open

DNS validation – “You cannot programmatically request that ACM automatically create your record in Route 53.” Automating everything was the goal, but DNS validation stayed stubbornly manual – the CNAME records must be created by hand.

CloudFront v2 logging – “If you’re provisioning CloudFront with CloudFormation, it’s easy to end up with the legacy setup by accident.” Ensuring v2 logging rather than the legacy default.

Wrapping up

When I started, I assumed this would be straightforward: create an S3 bucket, point DNS at the website endpoint, provision a certificate.

As usual, the reality involved unexpected twists:

  • CloudFront-hosted zones instead of your own, in Route 53 aliases
  • Origin access control instead of the deprecated origin access identity
  • Object ownership controls to allow the log delivery ACL to function
  • Everything in us-east-1, certificate and distribution alike
  • Vended log delivery, if you want the modern logging setup

Hopefully this helps anyone else looking to host a static website on S3 with a custom domain, CloudFront, and an SSL certificate.

Final Template

The final completed CloudFormation template for the static website resources looks like this:

Parameters:
  WebsiteName:
    Description: Name to use without dots
    Type: String

  WebsiteDomain:
    Description: Domain name of the website (e.g. example.com)
    Type: String

  WebsiteHostedZoneId:
    Description: Hosted Zone ID for DNS record creation
    Type: String

  LogRetentionDays:
    Description: >-
      Days to keep S3 and CloudFront request logs (queried with Athena via
      deploy/infra-monitoring.yml) before they're deleted
    Type: Number
    Default: 365
    MinValue: 1

  CspReportUrl:
    Description: >-
      URL browsers send CSP violation reports to (the ReportUrl output of
      deploy/infra-csp-reports.yml). Leave empty to send no reports.
    Type: String
    Default: ""

Conditions:
  HasCspReportUrl: !Not [!Equals [!Ref CspReportUrl, ""]]

Resources:
  WebsiteRecordSet:
    Type: AWS::Route53::RecordSetGroup
    DeletionPolicy: Delete
    Properties:
      HostedZoneId: !Ref WebsiteHostedZoneId
      RecordSets:
        - Name: !Ref WebsiteDomain
          Type: A
          AliasTarget:
            DNSName: !GetAtt CloudFrontDistribution.DomainName
            HostedZoneId: Z2FDTNDATAQYW2
        - Name: !Sub www.${WebsiteDomain}
          Type: A
          AliasTarget:
            DNSName: !GetAtt CloudFrontDistribution.DomainName
            HostedZoneId: Z2FDTNDATAQYW2
        - Name: !Ref WebsiteDomain
          Type: AAAA
          AliasTarget:
            DNSName: !GetAtt CloudFrontDistribution.DomainName
            HostedZoneId: Z2FDTNDATAQYW2
        - Name: !Sub www.${WebsiteDomain}
          Type: AAAA
          AliasTarget:
            DNSName: !GetAtt CloudFrontDistribution.DomainName
            HostedZoneId: Z2FDTNDATAQYW2

  WebsiteCertificate:
    Type: AWS::CertificateManager::Certificate
    DeletionPolicy: Delete
    Properties:
      DomainName: !Ref WebsiteDomain
      SubjectAlternativeNames:
        - !Sub www.${WebsiteDomain}
      DomainValidationOptions:
        - DomainName: !Sub ${WebsiteDomain}
          HostedZoneId: !Ref WebsiteHostedZoneId
      ValidationMethod: DNS

  WebsiteBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Delete
    Properties:
      BucketName: !Ref WebsiteDomain
      PublicAccessBlockConfiguration:
        RestrictPublicBuckets: true
        IgnorePublicAcls: true
        BlockPublicPolicy: true
        BlockPublicAcls: true
      LoggingConfiguration:
        DestinationBucketName: !Ref WebsiteRequestLoggingBucket
        TargetObjectKeyFormat:
          PartitionedPrefix:
            PartitionDateSource: EventTime

  WebsiteBucketPolicy:
    Type: AWS::S3::BucketPolicy
    DeletionPolicy: Delete
    Properties:
      Bucket: !Ref WebsiteBucket
      PolicyDocument:
        Version: 2012-10-17
        Id: PolicyForCloudFrontPrivateContent
        Statement:
          - Action: s3:GetObject
            Sid: AllowCloudFrontServicePrincipal
            Effect: Allow
            Principal:
              Service: cloudfront.amazonaws.com
            Resource: !Sub arn:${AWS::Partition}:s3:::${WebsiteBucket}/*
            Condition:
              StringEquals:
                'AWS:SourceArn': !Sub arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}
          - Action: 's3:*'
            Sid: DenyInsecureTransport
            Effect: Deny
            Principal: '*'
            Resource:
              - !Sub arn:${AWS::Partition}:s3:::${WebsiteBucket}
              - !Sub arn:${AWS::Partition}:s3:::${WebsiteBucket}/*
            Condition:
              Bool:
                'aws:SecureTransport': 'false'

  WebsiteRequestLoggingBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      BucketName: !Sub ${WebsiteDomain}-bucket-requests
      PublicAccessBlockConfiguration:
        RestrictPublicBuckets: true
        IgnorePublicAcls: true
        BlockPublicPolicy: true
        BlockPublicAcls: true
      LifecycleConfiguration:
        Rules:
        - Status: Enabled
          Id: Expire old logs
          ExpirationInDays: !Ref LogRetentionDays

  WebsiteRequestLoggingBucketPolicy:
    Type: AWS::S3::BucketPolicy
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      Bucket: !Ref WebsiteRequestLoggingBucket
      PolicyDocument:
        Version: 2012-10-17
        Id: PolicyForBucketRequestLogging
        Statement:
        - Action: s3:PutObject
          Sid: AllowS3LoggingServicePrincipal
          Effect: Allow
          Principal:
            Service: logging.s3.amazonaws.com
          Resource: !Sub arn:${AWS::Partition}:s3:::${WebsiteRequestLoggingBucket}/*
          Condition:
            StringEquals:
              aws:SourceAccount: !Ref AWS::AccountId

  CloudFrontRequestLoggingBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      BucketName: !Sub ${WebsiteDomain}-cloudfront-requests
      PublicAccessBlockConfiguration:
        RestrictPublicBuckets: true
        IgnorePublicAcls: true
        BlockPublicPolicy: true
        BlockPublicAcls: true
      LifecycleConfiguration:
        Rules:
        - Status: Enabled
          Id: Expire old logs
          ExpirationInDays: !Ref LogRetentionDays
      OwnershipControls:
        Rules:
        - ObjectOwnership: BucketOwnerPreferred

  CloudFrontRequestLoggingBucketPolicy:
    Type: AWS::S3::BucketPolicy
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      Bucket: !Ref CloudFrontRequestLoggingBucket
      PolicyDocument:
        Version: 2012-10-17
        Id: PolicyForCloudFrontRequestLogging
        Statement:
        - Action: s3:PutObject
          Sid: AllowLogDeliveryServicePrincipal
          Effect: Allow
          Principal:
            Service: delivery.logs.amazonaws.com
          Resource: !Sub arn:${AWS::Partition}:s3:::${CloudFrontRequestLoggingBucket}/AWSLogs/${AWS::AccountId}/CloudFront/*
          Condition:
            StringEquals:
              s3:x-amz-acl: bucket-owner-full-control
              aws:SourceAccount: !Ref AWS::AccountId
            ArnLike:
              aws:SourceArn: !Sub arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:delivery-source:CreatedByCloudFront-${CloudFrontDistribution.Id}

  CloudFrontDistribution:
    Type: AWS::CloudFront::Distribution
    DeletionPolicy: Delete
    Properties:
      DistributionConfig:
        Aliases:
          - !Ref WebsiteDomain
          - !Sub www.${WebsiteDomain}
        DefaultRootObject: index.html
        HttpVersion: http2and3
        IPV6Enabled: true
        Origins:
          - Id: !GetAtt WebsiteBucket.RegionalDomainName
            DomainName: !GetAtt WebsiteBucket.RegionalDomainName
            S3OriginConfig:
              OriginAccessIdentity: ''
            OriginAccessControlId: !GetAtt CloudFrontOriginAccessControl.Id
        Enabled: true
        DefaultCacheBehavior:
          TargetOriginId: !GetAtt WebsiteBucket.RegionalDomainName
          AllowedMethods:
            - GET
            - HEAD
          Compress: true
          ViewerProtocolPolicy: redirect-to-https
          CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6
          ResponseHeadersPolicyId: !Ref SecurityHeadersPolicy
          FunctionAssociations:
            - EventType: viewer-request
              FunctionARN: !GetAtt CloudFrontRewritePrettyUrlFunction.FunctionARN
        CustomErrorResponses:
          - ErrorCode: 403
            ResponseCode: 404
            ResponsePagePath: /404.html
            ErrorCachingMinTTL: 60
          - ErrorCode: 404
            ResponseCode: 404
            ResponsePagePath: /404.html
            ErrorCachingMinTTL: 60
        ViewerCertificate:
          AcmCertificateArn: !Ref WebsiteCertificate
          MinimumProtocolVersion: TLSv1.2_2021
          SslSupportMethod: sni-only

  CloudFrontRewritePrettyUrlFunction:
    Type: AWS::CloudFront::Function
    Properties:
      AutoPublish: true
      Name: maceage-blog-rewrite-pretty-urls
      FunctionConfig:
        Comment: 404 vulnerability probes; redirect www to the bare domain; enable pretty URLs for Hugo
        Runtime: cloudfront-js-2.0
      FunctionCode: |
        var PROBE = /\.php$|\.php\/|\/(wp-|\.env|\.git)/i;

        function queryString(qs) {
            var parts = [];
            for (var key in qs) {
                var values = qs[key].multiValue || [qs[key]];
                for (var i = 0; i < values.length; i++) {
                    parts.push(values[i].value === '' ? key : key + '=' + values[i].value);
                }
            }
            return parts.length ? '?' + parts.join('&') : '';
        }

        function handler(event) {
            var request = event.request;
            if (PROBE.test(request.uri)) {
                return {
                    statusCode: 404,
                    statusDescription: 'Not Found',
                    headers: {
                        'content-type': { value: 'text/plain' },
                        'cache-control': { value: 'public, max-age=86400' },
                        'x-content-type-options': { value: 'nosniff' }
                    },
                    body: { encoding: 'text', data: 'Not Found' }
                };
            }
            var host = request.headers.host ? request.headers.host.value : '';
            if (host.startsWith('www.')) {
                return {
                    statusCode: 301,
                    statusDescription: 'Moved Permanently',
                    headers: {
                        location: { value: 'https://' + host.slice(4) + request.uri + queryString(request.querystring) }
                    }
                };
            }
            var uri = request.uri;
            if (uri.endsWith('/')) {
                request.uri += 'index.html';
            } else if (!uri.slice(uri.lastIndexOf('/') + 1).includes('.')) {
                request.uri += '/index.html';
            }
            return request;
        }

  SecurityHeadersPolicy:
    Type: AWS::CloudFront::ResponseHeadersPolicy
    DeletionPolicy: Delete
    Properties:
      ResponseHeadersPolicyConfig:
        Name: !Sub ${WebsiteName}-security-headers
        Comment: Security headers, Permissions-Policy and a report-only Content-Security-Policy
        SecurityHeadersConfig:
          StrictTransportSecurity:
            AccessControlMaxAgeSec: 31536000
            Override: true
          ContentTypeOptions:
            Override: true
          FrameOptions:
            FrameOption: SAMEORIGIN
            Override: true
          ReferrerPolicy:
            ReferrerPolicy: strict-origin-when-cross-origin
            Override: true
          XSSProtection:
            Protection: false
            Override: true
        CustomHeadersConfig:
          Items:
            - Header: Permissions-Policy
              Override: true
              Value: >-
                camera=(), microphone=(), geolocation=(), payment=(),
                usb=(), serial=(), hid=(), midi=(), display-capture=(),
                browsing-topics=()
            - Header: Content-Security-Policy-Report-Only
              Override: true
              Value: !Join
                - ''
                - - >-
                    default-src 'self';
                    script-src 'self'
                    'sha256-39Zqt7USDaKXYnyFu43RoKSaKWOukkNxpUw+uK+NolQ='
                    'sha256-KfEK7rkBBc+JXGcAvP13f629b+LMq94vut2Uzu4v7NU='
                    'sha256-ZdU3LCEvugLQ+xTzltOgd1BRUKNZnVO6fzY80brkXXQ='
                    https://www.googletagmanager.com https://gc.zgo.at;
                    style-src 'self' 'unsafe-inline';
                    img-src 'self' data: https://*.google-analytics.com https://*.googletagmanager.com https://*.google.com https://*.g.doubleclick.net https://maceage.goatcounter.com;
                    connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com https://*.google.com https://*.g.doubleclick.net https://maceage.goatcounter.com;
                    font-src 'self';
                    frame-src https://www.youtube.com https://www.youtube-nocookie.com;
                    object-src 'none';
                    base-uri 'self';
                    form-action 'self';
                    frame-ancestors 'self'
                  - !If
                    - HasCspReportUrl
                    - !Sub '; report-uri ${CspReportUrl}; report-to csp'
                    - ''
            - !If
              - HasCspReportUrl
              - Header: Reporting-Endpoints
                Override: true
                Value: !Sub 'csp="${CspReportUrl}"'
              - !Ref AWS::NoValue

  CloudFrontOriginAccessControl:
    Type: AWS::CloudFront::OriginAccessControl
    DeletionPolicy: Delete
    Properties:
      OriginAccessControlConfig:
        Name: !GetAtt WebsiteBucket.RegionalDomainName
        OriginAccessControlOriginType: s3
        SigningBehavior: always
        SigningProtocol: sigv4

  CloudFrontAccessLogsDeliverySource:
    Type: AWS::Logs::DeliverySource
    DeletionPolicy: Delete
    Properties:
      LogType: ACCESS_LOGS
      Name: !Sub ${WebsiteName}-cloudfront-log-delivery-source
      ResourceArn: !Sub
        - arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:distribution/${Distribution}
        - Distribution: !GetAtt CloudFrontDistribution.Id

  CloudFrontAccessLogsDeliveryDestination:
    Type: AWS::Logs::DeliveryDestination
    DeletionPolicy: Delete
    Properties:
      DestinationResourceArn: !GetAtt CloudFrontRequestLoggingBucket.Arn
      Name: !Sub ${WebsiteName}-cloudfront-log-delivery-destination
      OutputFormat: json

  CloudFrontAccessLogsDelivery:
    Type: AWS::Logs::Delivery
    DeletionPolicy: Delete
    DependsOn: CloudFrontAccessLogsDeliverySource
    Properties:
      DeliveryDestinationArn: !GetAtt CloudFrontAccessLogsDeliveryDestination.Arn
      DeliverySourceName: !Sub ${WebsiteName}-cloudfront-log-delivery-source
      RecordFields:
        - date
        - time
        - x-edge-location
        - sc-bytes
        - c-ip
        - cs-method
        - 'cs(Host)'
        - cs-uri-stem
        - sc-status
        - 'cs(Referer)'
        - 'cs(User-Agent)'
        - cs-uri-query
        - x-edge-result-type
        - x-edge-request-id
        - x-host-header
        - cs-protocol
        - cs-bytes
        - time-taken
        - x-forwarded-for
        - ssl-protocol
        - ssl-cipher
        - x-edge-response-result-type
        - cs-protocol-version
        - fle-status
        - fle-encrypted-fields
        - c-port
        - time-to-first-byte
        - x-edge-detailed-result-type
        - sc-content-type
        - sc-content-len
        - sc-range-start
        - sc-range-end
        - c-country
        - asn
        - origin-fbl
        - origin-lbl
        - 'timestamp(ms)'
      S3SuffixPath: AWSLogs/{account-id}/CloudFront/{yyyy}/{MM}/{dd}/

Outputs:
  WebsiteDomain:
    Value: !Sub ${WebsiteDomain}
    Description: Website public domain address
  CloudFrontDistributionId:
    Value: !GetAtt CloudFrontDistribution.Id
    Description: CloudFront Distribution ID
  WebsiteBucketRegionalDomainName:
    Value: !GetAtt WebsiteBucket.RegionalDomainName
    Description: Regional domain name of WebsiteBucket