KKIMS on-site docs
AWS

CloudFront distribution for the website

Put the private website bucket behind CloudFront with Origin Access Control, the right cache, error pages, alternate domain and certificate; install the viewer-request function from deploy/cloudfront on main; later, redirects with a KeyValueStore; invalidations, logging, security headers and curl checks.

The public website is static files in the private website bucket, served by a CloudFront distribution. One distribution per environment. The Jenkins site build fills the bucket and invalidates the distribution after every deploy; CloudFront never talks to the CMS.

Warning

Without the viewer-request function only the home page works. The site stores every page as <address>/index.html and its links end in a slash (/bengaluru/doctors/). An S3 origin behind Origin Access Control does not add index.html by itself and answers 403 for a key it does not have. Install the function (below) before the first site build (main's runbook, step 8).

#Who does what

Task Usually done by What our engineer needs
Create the distribution and OAC KIMS's cloud team, or our engineer The distribution id (E...) and domain (d....cloudfront.net)
The website bucket's policy Same person
The viewer-request function Someone who can edit the distribution, with our engineer reading the steps
The redirects KeyValueStore (later) Same Its ARN, for KIMS_REDIRECTS_KVS_ARN
Invalidations Nobody by hand: the site build does it CLOUDFRONT_DISTRIBUTION_ID in kims-site-env
Pointing the website host at CloudFront KIMS's DNS team, at a time KIMS decides Certificates and DNS

#The settings

From main's runbook (AWS set-up C and step 8):

Setting Value Why
Distribution type Standard, Single website or app
Pricing plan (if the console offers one) Pay as you go The plain one
Origin The website bucket's REST endpoint <WEBSITE_BUCKET>.s3.<REGION>.amazonaws.com, never the s3-website endpoint OAC only works with the REST endpoint
Origin access Origin access control, new OAC kims-website-oac (UAT kims-uat-website-oac), Sign requests (recommended) The bucket stays private
Viewer protocol policy Redirect HTTP to HTTPS
Allowed HTTP methods GET, HEAD Static site
Compress objects automatically Yes
Cache policy CachingOptimized (managed, id 658327ea-f89d-4fab-a63d-7e88639e58f6) Follows the Cache-Control the site build puts on each file: pages no-cache, must-revalidate, hashed assets and media a year immutable, data files 5 minutes (scripts/deploy/cache-rules.mjs)
Origin request policy None No headers or query strings needed at the origin
Function associations Viewer request: CloudFront Functions, kims-viewer-request Directory URLs (and redirects later)
Web Application Firewall KIMS's call (it costs extra) The site works either way
Price class Use North America, Europe, Asia, Middle East, and Africa Includes India, costs less than all edge locations
Alternate domain name The website host (and the bare domain if the certificate covers it)
Custom SSL certificate The us-east-1 certificate (Certificates)
Security policy TLSv1.2_2021 (the console's recommended)
Supported HTTP versions HTTP/2 and HTTP/3
Default root object index.html The home page
Custom error responses 403 and 404, each: response page /404.html, response code 404, error caching minimum TTL 10 s S3 answers 403, not 404, for a missing key behind OAC. Without these, a wrong address shows S3's XML error
Standard logging Optional See Logging

Every language's missing page gets the English /404.html.

#Create the distribution: console steps

The console's screens change from time to time; the settings above are what matter. This is the 2026 wizard.

  1. CloudFront console > Distributions > Create distribution.
  2. If a Choose a plan step appears: Pay as you go.
  3. Distribution name: kims-website-prod (UAT kims-website-uat). Choose Single website or app > Next.
  4. Domain setup (if shown): skip it unless KIMS's DNS is Route 53 in this account. Next.
  5. Specify origin: Origin type Amazon S3. S3 origin: Browse S3, choose the website bucket. Check the address is <WEBSITE_BUCKET>.s3.<REGION>.amazonaws.com; if a suggestion to use the website endpoint appears, decline it.
  6. Settings: Use recommended origin settings (it creates an Origin Access Control and uses CachingOptimized). If you choose Customize origin settings, pick Origin access control, Create new OAC kims-website-oac, Sign requests (recommended).
  7. Next. Enable security protections: KIMS's call. Next.
  8. Review, Create distribution. CloudFront offers to update the bucket policy; let it, then check it against The website bucket policy.
  9. Open the new distribution. On the General tab > Settings > Edit:
    • Price class: Use North America, Europe, Asia, Middle East, and Africa.
    • Alternate domain name (CNAME): Add item, the website host (see Alternate domain name and certificate before production go-live).
    • Custom SSL certificate: the us-east-1 certificate.
    • Supported HTTP versions: tick HTTP/2 and HTTP/3.
    • Default root object: index.html.
    • Save changes.
  10. Behaviors tab > select Default (*) > Edit: Viewer protocol policy Redirect HTTP to HTTPS; Allowed HTTP methods GET, HEAD; Compress objects automatically Yes; Cache policy CachingOptimized; no origin request policy. Save changes. (The function association is added in Associate the function.)
  11. Error pages tab > Create custom error response: HTTP error code 403: Forbidden, Error caching minimum TTL 10, Customize error response Yes, Response page path /404.html, HTTP Response code 404: Not Found > Create custom error response. Repeat for 404: Not Found.
  12. Copy the Distribution ID (E...) and the Distribution domain name (d....cloudfront.net).

The distribution's Last modified shows Deploying for a few minutes, then a date.

#Create the distribution: CLI steps

The CLI makes the OAC, the distribution and (after) the bucket policy. Create the function first (below) if you want it in the same step; otherwise leave FunctionAssociations out and add it later.

#Set the names once

bash
export AWS_REGION=ap-south-2
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
WEBSITE_BUCKET=kims-hospitals-website-prod
SITE_HOST=<SITE_HOST>
SITE_CERT_ARN=<SITE_CERT_ARN_IN_US_EAST_1>
REPO=<PATH_TO_KIMS_V2_ON_MAIN>
bash
export AWS_REGION=ap-south-2
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
WEBSITE_BUCKET=kims-hospitals-website-prod
SITE_HOST=<SITE_HOST>
SITE_CERT_ARN=<SITE_CERT_ARN_IN_US_EAST_1>
REPO=<PATH_TO_KIMS_V2_ON_MAIN>
powershell
$env:AWS_REGION = "ap-south-2"
$Account       = aws sts get-caller-identity --query Account --output text
$WebsiteBucket = "kims-hospitals-website-prod"
$SiteHost      = "<SITE_HOST>"
$SiteCertArn   = "<SITE_CERT_ARN_IN_US_EAST_1>"
$Repo          = "<PATH_TO_KIMS_V2_ON_MAIN>"

REPO is a checkout of kims-v2 on main (git -C <REPO> rev-parse --abbrev-ref HEAD says main).

#The origin access control

bash
OAC_ID=$(aws cloudfront create-origin-access-control \
  --origin-access-control-config Name=kims-website-oac,SigningProtocol=sigv4,SigningBehavior=always,OriginAccessControlOriginType=s3 \
  --query OriginAccessControl.Id --output text)
echo "$OAC_ID"
bash
OAC_ID=$(aws cloudfront create-origin-access-control \
  --origin-access-control-config Name=kims-website-oac,SigningProtocol=sigv4,SigningBehavior=always,OriginAccessControlOriginType=s3 \
  --query OriginAccessControl.Id --output text)
echo "$OAC_ID"
powershell
$OacId = aws cloudfront create-origin-access-control `
  --origin-access-control-config "Name=kims-website-oac,SigningProtocol=sigv4,SigningBehavior=always,OriginAccessControlOriginType=s3" `
  --query OriginAccessControl.Id --output text
$OacId

#The distribution

bash
cat > distribution.json <<EOF
{
  "CallerReference": "kims-website-prod-$(date +%Y%m%d%H%M%S)",
  "Comment": "KIMS website (production)",
  "Enabled": true,
  "HttpVersion": "http2and3",
  "PriceClass": "PriceClass_200",
  "DefaultRootObject": "index.html",
  "Aliases": { "Quantity": 1, "Items": ["$SITE_HOST"] },
  "Origins": {
    "Quantity": 1,
    "Items": [
      {
        "Id": "website",
        "DomainName": "$WEBSITE_BUCKET.s3.$AWS_REGION.amazonaws.com",
        "OriginAccessControlId": "$OAC_ID",
        "S3OriginConfig": { "OriginAccessIdentity": "" }
      }
    ]
  },
  "DefaultCacheBehavior": {
    "TargetOriginId": "website",
    "ViewerProtocolPolicy": "redirect-to-https",
    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
    "Compress": true,
    "AllowedMethods": {
      "Quantity": 2, "Items": ["GET", "HEAD"],
      "CachedMethods": { "Quantity": 2, "Items": ["GET", "HEAD"] }
    }
  },
  "CustomErrorResponses": {
    "Quantity": 2,
    "Items": [
      { "ErrorCode": 403, "ResponsePagePath": "/404.html", "ResponseCode": "404", "ErrorCachingMinTTL": 10 },
      { "ErrorCode": 404, "ResponsePagePath": "/404.html", "ResponseCode": "404", "ErrorCachingMinTTL": 10 }
    ]
  },
  "ViewerCertificate": {
    "ACMCertificateArn": "$SITE_CERT_ARN",
    "SSLSupportMethod": "sni-only",
    "MinimumProtocolVersion": "TLSv1.2_2021"
  }
}
EOF
aws cloudfront create-distribution --distribution-config file://distribution.json \
  --query "Distribution.{id:Id,arn:ARN,domain:DomainName,status:Status}" > distribution-created.json
cat distribution-created.json
DIST_ID=$(python3 -c 'import json;print(json.load(open("distribution-created.json"))["id"])')
DIST_ARN=$(python3 -c 'import json;print(json.load(open("distribution-created.json"))["arn"])')
bash
cat > distribution.json <<EOF
{
  "CallerReference": "kims-website-prod-$(date +%Y%m%d%H%M%S)",
  "Comment": "KIMS website (production)",
  "Enabled": true,
  "HttpVersion": "http2and3",
  "PriceClass": "PriceClass_200",
  "DefaultRootObject": "index.html",
  "Aliases": { "Quantity": 1, "Items": ["$SITE_HOST"] },
  "Origins": {
    "Quantity": 1,
    "Items": [
      {
        "Id": "website",
        "DomainName": "$WEBSITE_BUCKET.s3.$AWS_REGION.amazonaws.com",
        "OriginAccessControlId": "$OAC_ID",
        "S3OriginConfig": { "OriginAccessIdentity": "" }
      }
    ]
  },
  "DefaultCacheBehavior": {
    "TargetOriginId": "website",
    "ViewerProtocolPolicy": "redirect-to-https",
    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
    "Compress": true,
    "AllowedMethods": {
      "Quantity": 2, "Items": ["GET", "HEAD"],
      "CachedMethods": { "Quantity": 2, "Items": ["GET", "HEAD"] }
    }
  },
  "CustomErrorResponses": {
    "Quantity": 2,
    "Items": [
      { "ErrorCode": 403, "ResponsePagePath": "/404.html", "ResponseCode": "404", "ErrorCachingMinTTL": 10 },
      { "ErrorCode": 404, "ResponsePagePath": "/404.html", "ResponseCode": "404", "ErrorCachingMinTTL": 10 }
    ]
  },
  "ViewerCertificate": {
    "ACMCertificateArn": "$SITE_CERT_ARN",
    "SSLSupportMethod": "sni-only",
    "MinimumProtocolVersion": "TLSv1.2_2021"
  }
}
EOF
aws cloudfront create-distribution --distribution-config file://distribution.json \
  --query "Distribution.{id:Id,arn:ARN,domain:DomainName,status:Status}" > distribution-created.json
cat distribution-created.json
DIST_ID=$(python3 -c 'import json;print(json.load(open("distribution-created.json"))["id"])')
DIST_ARN=$(python3 -c 'import json;print(json.load(open("distribution-created.json"))["arn"])')
powershell
@"
{
  "CallerReference": "kims-website-prod-$(Get-Date -Format yyyyMMddHHmmss)",
  "Comment": "KIMS website (production)",
  "Enabled": true,
  "HttpVersion": "http2and3",
  "PriceClass": "PriceClass_200",
  "DefaultRootObject": "index.html",
  "Aliases": { "Quantity": 1, "Items": ["$SiteHost"] },
  "Origins": {
    "Quantity": 1,
    "Items": [
      {
        "Id": "website",
        "DomainName": "$WebsiteBucket.s3.$($env:AWS_REGION).amazonaws.com",
        "OriginAccessControlId": "$OacId",
        "S3OriginConfig": { "OriginAccessIdentity": "" }
      }
    ]
  },
  "DefaultCacheBehavior": {
    "TargetOriginId": "website",
    "ViewerProtocolPolicy": "redirect-to-https",
    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
    "Compress": true,
    "AllowedMethods": {
      "Quantity": 2, "Items": ["GET", "HEAD"],
      "CachedMethods": { "Quantity": 2, "Items": ["GET", "HEAD"] }
    }
  },
  "CustomErrorResponses": {
    "Quantity": 2,
    "Items": [
      { "ErrorCode": 403, "ResponsePagePath": "/404.html", "ResponseCode": "404", "ErrorCachingMinTTL": 10 },
      { "ErrorCode": 404, "ResponsePagePath": "/404.html", "ResponseCode": "404", "ErrorCachingMinTTL": 10 }
    ]
  },
  "ViewerCertificate": {
    "ACMCertificateArn": "$SiteCertArn",
    "SSLSupportMethod": "sni-only",
    "MinimumProtocolVersion": "TLSv1.2_2021"
  }
}
"@ | Set-Content -Encoding ascii distribution.json
$Dist = aws cloudfront create-distribution --distribution-config file://distribution.json | ConvertFrom-Json
$DistId  = $Dist.Distribution.Id
$DistArn = $Dist.Distribution.ARN
"$DistId  $DistArn  $($Dist.Distribution.DomainName)"

You should see the id (E...), the ARN (arn:aws:cloudfront::<AWS_ACCOUNT_ID>:distribution/E...), and the domain (d....cloudfront.net). If the host is still served by the old platform, see Alternate domain name and certificate first.

#The website bucket policy

Only this distribution may read the website bucket. From main's runbook, step C9:

json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowCloudFrontRead",
      "Effect": "Allow",
      "Principal": { "Service": "cloudfront.amazonaws.com" },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::<WEBSITE_BUCKET>/*",
      "Condition": {
        "StringEquals": {
          "AWS:SourceArn": "arn:aws:cloudfront::<AWS_ACCOUNT_ID>:distribution/<DISTRIBUTION_ID>"
        }
      }
    }
  ]
}

No s3:ListBucket: a missing page is then a 403 (which the error responses turn into the 404 page) rather than a listing-backed 404, and nobody can enumerate the bucket.

Console: S3 > the website bucket > Permissions > Bucket policy > Edit > paste, values filled in > Save changes. The console's "copy policy" banner on the distribution gives the same thing.

bash
cat > website-bucket-policy.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowCloudFrontRead",
      "Effect": "Allow",
      "Principal": { "Service": "cloudfront.amazonaws.com" },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::$WEBSITE_BUCKET/*",
      "Condition": { "StringEquals": { "AWS:SourceArn": "$DIST_ARN" } }
    }
  ]
}
EOF
aws s3api put-bucket-policy --bucket "$WEBSITE_BUCKET" --policy file://website-bucket-policy.json
bash
cat > website-bucket-policy.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowCloudFrontRead",
      "Effect": "Allow",
      "Principal": { "Service": "cloudfront.amazonaws.com" },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::$WEBSITE_BUCKET/*",
      "Condition": { "StringEquals": { "AWS:SourceArn": "$DIST_ARN" } }
    }
  ]
}
EOF
aws s3api put-bucket-policy --bucket "$WEBSITE_BUCKET" --policy file://website-bucket-policy.json
powershell
@"
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowCloudFrontRead",
      "Effect": "Allow",
      "Principal": { "Service": "cloudfront.amazonaws.com" },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::$WebsiteBucket/*",
      "Condition": { "StringEquals": { "AWS:SourceArn": "$DistArn" } }
    }
  ]
}
"@ | Set-Content -Encoding ascii website-bucket-policy.json
aws s3api put-bucket-policy --bucket $WebsiteBucket --policy file://website-bucket-policy.json

#Alternate domain name and certificate

  • The certificate must be Issued, in us-east-1, and cover the host (Certificates).
  • Production while the old platform is live: if the old site's CloudFront distribution still holds the production host, adding it here fails with CNAMEAlreadyExists. Leave the alternate domain out (in the CLI JSON: "Aliases": { "Quantity": 0 }), check production on d....cloudfront.net, and add the host at go-live as agreed with KIMS (Production cutover). Moving a host between distributions is done by AWS's "move alternate domain name" procedure, which KIMS's cloud team runs.

#The viewer-request function

Use the files on main, in deploy/cloudfront/:

File What it does When
viewer-request.js Adds index.html: /about/ becomes /about/index.html, and /about (no dot anywhere in the address) becomes /about/index.html too The first day. No KeyValueStore needed
viewer-request-redirects.js Looks the address up in a KeyValueStore first and answers 301/302 on a hit; then adds index.html like the other Only once a redirects KeyValueStore exists and is associated with the function (Redirects KeyValueStore)
Warning

viewer-request-redirects.js calls cf.kvs() when the function starts. With no store associated that line throws, and every request fails, not only redirects. Never publish it on a function that has no KeyValueStore.

Both are runtime cloudfront-js-2.0. That runtime rejects some modern JavaScript at parse time (catch { without a binding, optional chaining, spread, for...of, destructuring); tests/cloudfront-functions.test.ts checks the files for them. Paste the file as it is.

#Create, test and publish: console steps

  1. CloudFront console > left menu Functions > Create function.
  2. Name kims-viewer-request (UAT: the same function can serve both distributions, or make kims-uat-viewer-request). Description KIMS website: directory URLs. Runtime cloudfront-js-2.0. Create function.
  3. Build tab: replace the example code with the whole of deploy/cloudfront/viewer-request.js from main > Save changes.
  4. Test tab: Event type Viewer Request, Stage Development, HTTP method GET, URL path /bengaluru/doctors/ > Test function. Execution result: Output shows "uri": "/bengaluru/doctors/index.html", and Compute utilization is low (under 20).
  5. Test again with /bengaluru/doctors (no slash): the same output URI. And /assets/logo.png: the URI unchanged.
  6. Publish tab > Publish function.

#Create, test and publish: CLI steps

bash
aws cloudfront create-function --name kims-viewer-request \
  --function-config Comment="KIMS website: directory URLs",Runtime=cloudfront-js-2.0 \
  --function-code "fileb://$REPO/deploy/cloudfront/viewer-request.js" \
  --query "FunctionSummary.FunctionMetadata.Stage" --output text
cat > test-event.json <<'EOF'
{
  "version": "1.0",
  "context": { "eventType": "viewer-request" },
  "viewer": { "ip": "198.51.100.1" },
  "request": { "method": "GET", "uri": "/bengaluru/doctors/", "headers": {}, "cookies": {}, "querystring": {} }
}
EOF
FN_ETAG=$(aws cloudfront describe-function --name kims-viewer-request --stage DEVELOPMENT --query ETag --output text)
aws cloudfront test-function --name kims-viewer-request --if-match "$FN_ETAG" --stage DEVELOPMENT \
  --event-object fileb://test-event.json \
  --query "TestResult.{error:FunctionErrorMessage,output:FunctionOutput,utilization:ComputeUtilization}"
aws cloudfront publish-function --name kims-viewer-request --if-match "$FN_ETAG"
FN_ARN=$(aws cloudfront describe-function --name kims-viewer-request --stage LIVE \
  --query FunctionSummary.FunctionMetadata.FunctionARN --output text)
echo "$FN_ARN"
bash
aws cloudfront create-function --name kims-viewer-request \
  --function-config Comment="KIMS website: directory URLs",Runtime=cloudfront-js-2.0 \
  --function-code "fileb://$REPO/deploy/cloudfront/viewer-request.js" \
  --query "FunctionSummary.FunctionMetadata.Stage" --output text
cat > test-event.json <<'EOF'
{
  "version": "1.0",
  "context": { "eventType": "viewer-request" },
  "viewer": { "ip": "198.51.100.1" },
  "request": { "method": "GET", "uri": "/bengaluru/doctors/", "headers": {}, "cookies": {}, "querystring": {} }
}
EOF
FN_ETAG=$(aws cloudfront describe-function --name kims-viewer-request --stage DEVELOPMENT --query ETag --output text)
aws cloudfront test-function --name kims-viewer-request --if-match "$FN_ETAG" --stage DEVELOPMENT \
  --event-object fileb://test-event.json \
  --query "TestResult.{error:FunctionErrorMessage,output:FunctionOutput,utilization:ComputeUtilization}"
aws cloudfront publish-function --name kims-viewer-request --if-match "$FN_ETAG"
FN_ARN=$(aws cloudfront describe-function --name kims-viewer-request --stage LIVE \
  --query FunctionSummary.FunctionMetadata.FunctionARN --output text)
echo "$FN_ARN"
powershell
aws cloudfront create-function --name kims-viewer-request `
  --function-config "Comment=KIMS website: directory URLs,Runtime=cloudfront-js-2.0" `
  --function-code "fileb://$Repo\deploy\cloudfront\viewer-request.js" `
  --query "FunctionSummary.FunctionMetadata.Stage" --output text
@'
{
  "version": "1.0",
  "context": { "eventType": "viewer-request" },
  "viewer": { "ip": "198.51.100.1" },
  "request": { "method": "GET", "uri": "/bengaluru/doctors/", "headers": {}, "cookies": {}, "querystring": {} }
}
'@ | Set-Content -Encoding ascii test-event.json
$FnEtag = aws cloudfront describe-function --name kims-viewer-request --stage DEVELOPMENT --query ETag --output text
aws cloudfront test-function --name kims-viewer-request --if-match $FnEtag --stage DEVELOPMENT `
  --event-object fileb://test-event.json `
  --query "TestResult.{error:FunctionErrorMessage,output:FunctionOutput,utilization:ComputeUtilization}"
aws cloudfront publish-function --name kims-viewer-request --if-match $FnEtag
$FnArn = aws cloudfront describe-function --name kims-viewer-request --stage LIVE `
  --query FunctionSummary.FunctionMetadata.FunctionARN --output text
$FnArn

create-function prints DEVELOPMENT. The test shows "error": null (or empty) and an output containing "uri":"/bengaluru/doctors/index.html". publish-function prints the function with "Stage": "LIVE". The ARN looks like arn:aws:cloudfront::<AWS_ACCOUNT_ID>:function/kims-viewer-request.

#Associate the function with the distribution

Console: the distribution > Behaviors tab > Default (*) > Edit > Function associations > Viewer request: Function type CloudFront Functions, Function ARN / Name kims-viewer-request > Save changes. Wait for Last modified to show a date (a few minutes). Or from the function: Publish tab > Add association > the distribution, Event type Viewer Request, Cache behavior Default (*) > Add association.

CLI: read the distribution's config, set the association, write it back with the ETag.

bash
DIST_ID=<DISTRIBUTION_ID>
aws cloudfront get-distribution-config --id "$DIST_ID" > current.json
ETAG=$(jq -r .ETag current.json)
jq --arg arn "$FN_ARN" '.DistributionConfig
  | .DefaultCacheBehavior.FunctionAssociations = {Quantity: 1, Items: [{FunctionARN: $arn, EventType: "viewer-request"}]}' \
  current.json > dist-config.json
aws cloudfront update-distribution --id "$DIST_ID" --if-match "$ETAG" \
  --distribution-config file://dist-config.json --query Distribution.Status --output text
aws cloudfront wait distribution-deployed --id "$DIST_ID"
bash
DIST_ID=<DISTRIBUTION_ID>
aws cloudfront get-distribution-config --id "$DIST_ID" > current.json
ETAG=$(jq -r .ETag current.json)
jq --arg arn "$FN_ARN" '.DistributionConfig
  | .DefaultCacheBehavior.FunctionAssociations = {Quantity: 1, Items: [{FunctionARN: $arn, EventType: "viewer-request"}]}' \
  current.json > dist-config.json
aws cloudfront update-distribution --id "$DIST_ID" --if-match "$ETAG" \
  --distribution-config file://dist-config.json --query Distribution.Status --output text
aws cloudfront wait distribution-deployed --id "$DIST_ID"
powershell
$DistId = "<DISTRIBUTION_ID>"
$Current = aws cloudfront get-distribution-config --id $DistId | ConvertFrom-Json
$Config = $Current.DistributionConfig
$Config.DefaultCacheBehavior.FunctionAssociations = [pscustomobject]@{
  Quantity = 1
  Items = @([pscustomobject]@{ FunctionARN = $FnArn; EventType = "viewer-request" })
}
$Config | ConvertTo-Json -Depth 50 | Set-Content -Encoding ascii dist-config.json
aws cloudfront update-distribution --id $DistId --if-match $Current.ETag `
  --distribution-config file://dist-config.json --query Distribution.Status --output text
aws cloudfront wait distribution-deployed --id $DistId

update-distribution prints InProgress; the wait returns when it is Deployed (5 to 15 minutes). jq is in Other tools. Keep -Depth 50 on Windows: ConvertTo-Json silently flattens anything deeper than its default of 2.

#Updating the function later

When deploy/cloudfront/viewer-request.js changes on main. The distribution does not change; publishing replaces what runs, at every edge within minutes. The site build never updates the function.

bash
FN_ETAG=$(aws cloudfront describe-function --name kims-viewer-request --stage DEVELOPMENT --query ETag --output text)
FN_ETAG=$(aws cloudfront update-function --name kims-viewer-request --if-match "$FN_ETAG" \
  --function-config Comment="KIMS website: directory URLs",Runtime=cloudfront-js-2.0 \
  --function-code "fileb://$REPO/deploy/cloudfront/viewer-request.js" --query ETag --output text)
aws cloudfront test-function --name kims-viewer-request --if-match "$FN_ETAG" --stage DEVELOPMENT \
  --event-object fileb://test-event.json --query "TestResult.{error:FunctionErrorMessage,output:FunctionOutput}"
aws cloudfront publish-function --name kims-viewer-request --if-match "$FN_ETAG"
bash
FN_ETAG=$(aws cloudfront describe-function --name kims-viewer-request --stage DEVELOPMENT --query ETag --output text)
FN_ETAG=$(aws cloudfront update-function --name kims-viewer-request --if-match "$FN_ETAG" \
  --function-config Comment="KIMS website: directory URLs",Runtime=cloudfront-js-2.0 \
  --function-code "fileb://$REPO/deploy/cloudfront/viewer-request.js" --query ETag --output text)
aws cloudfront test-function --name kims-viewer-request --if-match "$FN_ETAG" --stage DEVELOPMENT \
  --event-object fileb://test-event.json --query "TestResult.{error:FunctionErrorMessage,output:FunctionOutput}"
aws cloudfront publish-function --name kims-viewer-request --if-match "$FN_ETAG"
powershell
$FnEtag = aws cloudfront describe-function --name kims-viewer-request --stage DEVELOPMENT --query ETag --output text
$FnEtag = aws cloudfront update-function --name kims-viewer-request --if-match $FnEtag `
  --function-config "Comment=KIMS website: directory URLs,Runtime=cloudfront-js-2.0" `
  --function-code "fileb://$Repo\deploy\cloudfront\viewer-request.js" --query ETag --output text
aws cloudfront test-function --name kims-viewer-request --if-match $FnEtag --stage DEVELOPMENT `
  --event-object fileb://test-event.json --query "TestResult.{error:FunctionErrorMessage,output:FunctionOutput}"
aws cloudfront publish-function --name kims-viewer-request --if-match $FnEtag

#Redirects KeyValueStore (later)

Not needed on the first day: no redirects are stored yet, and whether redirects use a KeyValueStore is still open with KIMS (README-site.md on main). When KIMS wants old addresses to point at new pages, do these in this order:

  1. Create the store. Console: CloudFront > Functions > KeyValueStores tab > Create KeyValueStore > Name kims-redirects-prod (UAT kims-redirects-uat) > no import > Create. Wait for Status Ready, and copy its ARN.
  2. Associate it with the function. Functions > kims-viewer-request > Associate KeyValueStore > Associate existing KeyValueStore > the store > Associate KeyValueStore. A function can have only one store.
  3. Replace the code with deploy/cloudfront/viewer-request-redirects.js from main > Save changes.
  4. Test /bengaluru/doctors/ again: output URI /bengaluru/doctors/index.html, no error. An error mentioning the store means step 2 did not take: do not publish.
  5. Publish function.
  6. Add KIMS_REDIRECTS_KVS_ARN=<KVS_ARN> to the environment's kims-site-env credential (Site job), and the Redirects statement to the agent's role (IAM). The next site build fills the store from the CMS Redirects screen.

CLI for steps 1 to 5 (the store's ARN goes into the function config):

bash
KVS_ARN=$(aws cloudfront create-key-value-store --name kims-redirects-prod \
  --comment "KIMS website redirects, written by the site build" --query KeyValueStore.ARN --output text)
aws cloudfront describe-key-value-store --name kims-redirects-prod --query KeyValueStore.Status --output text
cat > function-config.json <<EOF
{ "Comment": "KIMS website: redirects and directory URLs", "Runtime": "cloudfront-js-2.0",
  "KeyValueStoreAssociations": { "Quantity": 1, "Items": [ { "KeyValueStoreARN": "$KVS_ARN" } ] } }
EOF
FN_ETAG=$(aws cloudfront describe-function --name kims-viewer-request --stage DEVELOPMENT --query ETag --output text)
FN_ETAG=$(aws cloudfront update-function --name kims-viewer-request --if-match "$FN_ETAG" \
  --function-config file://function-config.json \
  --function-code "fileb://$REPO/deploy/cloudfront/viewer-request-redirects.js" --query ETag --output text)
aws cloudfront test-function --name kims-viewer-request --if-match "$FN_ETAG" --stage DEVELOPMENT \
  --event-object fileb://test-event.json --query "TestResult.{error:FunctionErrorMessage,output:FunctionOutput}"
aws cloudfront publish-function --name kims-viewer-request --if-match "$FN_ETAG"
echo "$KVS_ARN"
bash
KVS_ARN=$(aws cloudfront create-key-value-store --name kims-redirects-prod \
  --comment "KIMS website redirects, written by the site build" --query KeyValueStore.ARN --output text)
aws cloudfront describe-key-value-store --name kims-redirects-prod --query KeyValueStore.Status --output text
cat > function-config.json <<EOF
{ "Comment": "KIMS website: redirects and directory URLs", "Runtime": "cloudfront-js-2.0",
  "KeyValueStoreAssociations": { "Quantity": 1, "Items": [ { "KeyValueStoreARN": "$KVS_ARN" } ] } }
EOF
FN_ETAG=$(aws cloudfront describe-function --name kims-viewer-request --stage DEVELOPMENT --query ETag --output text)
FN_ETAG=$(aws cloudfront update-function --name kims-viewer-request --if-match "$FN_ETAG" \
  --function-config file://function-config.json \
  --function-code "fileb://$REPO/deploy/cloudfront/viewer-request-redirects.js" --query ETag --output text)
aws cloudfront test-function --name kims-viewer-request --if-match "$FN_ETAG" --stage DEVELOPMENT \
  --event-object fileb://test-event.json --query "TestResult.{error:FunctionErrorMessage,output:FunctionOutput}"
aws cloudfront publish-function --name kims-viewer-request --if-match "$FN_ETAG"
echo "$KVS_ARN"
powershell
$KvsArn = aws cloudfront create-key-value-store --name kims-redirects-prod `
  --comment "KIMS website redirects, written by the site build" --query KeyValueStore.ARN --output text
aws cloudfront describe-key-value-store --name kims-redirects-prod --query KeyValueStore.Status --output text
@"
{ "Comment": "KIMS website: redirects and directory URLs", "Runtime": "cloudfront-js-2.0",
  "KeyValueStoreAssociations": { "Quantity": 1, "Items": [ { "KeyValueStoreARN": "$KvsArn" } ] } }
"@ | Set-Content -Encoding ascii function-config.json
$FnEtag = aws cloudfront describe-function --name kims-viewer-request --stage DEVELOPMENT --query ETag --output text
$FnEtag = aws cloudfront update-function --name kims-viewer-request --if-match $FnEtag `
  --function-config file://function-config.json `
  --function-code "fileb://$Repo\deploy\cloudfront\viewer-request-redirects.js" --query ETag --output text
aws cloudfront test-function --name kims-viewer-request --if-match $FnEtag --stage DEVELOPMENT `
  --event-object fileb://test-event.json --query "TestResult.{error:FunctionErrorMessage,output:FunctionOutput}"
aws cloudfront publish-function --name kims-viewer-request --if-match $FnEtag
$KvsArn

Wait until describe-key-value-store says READY before the update-function. The KVS ARN looks like arn:aws:cloudfront::<AWS_ACCOUNT_ID>:key-value-store/<KVS_ID>.

Store limits: key 512 bytes, value 1 KB, whole store 5 MB, 50 keys per update call (the site build batches by 50). After a build with redirects, check what it wrote:

bash
aws cloudfront-keyvaluestore describe-key-value-store --kvs-arn "$KVS_ARN" --query "{keys:ItemCount,status:Status}"
aws cloudfront-keyvaluestore list-keys --kvs-arn "$KVS_ARN" --max-results 5
bash
aws cloudfront-keyvaluestore describe-key-value-store --kvs-arn "$KVS_ARN" --query "{keys:ItemCount,status:Status}"
aws cloudfront-keyvaluestore list-keys --kvs-arn "$KVS_ARN" --max-results 5
powershell
aws cloudfront-keyvaluestore describe-key-value-store --kvs-arn $KvsArn --query "{keys:ItemCount,status:Status}"
aws cloudfront-keyvaluestore list-keys --kvs-arn $KvsArn --max-results 5

Each value is JSON like {"to":"/bengaluru/hospitals/mahadevapura/contact/","status":301}, the key being the old path without a trailing slash.

#Invalidations

The site build invalidates after every deploy (scripts/site-build/cloudfront.mjs, paths from scripts/deploy/cache-rules.mjs). For the three shipped languages it sends 14 paths, all wildcards or roots, and never /_next/static/* or /media/* (their file names change when their content does):

text
/*.html  /*.txt  /  /kn/  /hi/  /data/*  /kn/data/*  /hi/data/*
/sitemap.xml  /kn/sitemap.xml  /hi/sitemap.xml  /robots.txt  /kn/robots.txt  /hi/robots.txt

If the invalidation fails three times, the build records a warning, not a failure: the bucket already has the new site and pages are no-cache. To run it by hand (the warning text gives the same paths):

bash
aws cloudfront create-invalidation --distribution-id <DISTRIBUTION_ID> \
  --paths "/*.html" "/*.txt" "/" "/kn/" "/hi/" "/data/*" "/kn/data/*" "/hi/data/*" \
  "/sitemap.xml" "/kn/sitemap.xml" "/hi/sitemap.xml" "/robots.txt" "/kn/robots.txt" "/hi/robots.txt" \
  --query "Invalidation.{id:Id,status:Status}"
bash
aws cloudfront create-invalidation --distribution-id <DISTRIBUTION_ID> \
  --paths "/*.html" "/*.txt" "/" "/kn/" "/hi/" "/data/*" "/kn/data/*" "/hi/data/*" \
  "/sitemap.xml" "/kn/sitemap.xml" "/hi/sitemap.xml" "/robots.txt" "/kn/robots.txt" "/hi/robots.txt" \
  --query "Invalidation.{id:Id,status:Status}"
powershell
aws cloudfront create-invalidation --distribution-id <DISTRIBUTION_ID> `
  --paths "/*.html" "/*.txt" "/" "/kn/" "/hi/" "/data/*" "/kn/data/*" "/hi/data/*" `
  "/sitemap.xml" "/kn/sitemap.xml" "/hi/sitemap.xml" "/robots.txt" "/kn/robots.txt" "/hi/robots.txt" `
  --query "Invalidation.{id:Id,status:Status}"

It prints an id and InProgress; aws cloudfront get-invalidation --distribution-id <DISTRIBUTION_ID> --id <ID> shows Completed within a minute or two. Do not invalidate /*: it is one path for billing but sweeps every hashed asset for nothing.

#Logging

Optional, KIMS's choice. CloudFront standard logging (v2) delivers access logs to S3, CloudWatch Logs or Data Firehose.

Console: the distribution > Logging tab > Add > Amazon S3 (or Amazon CloudWatch Logs) > the destination bucket (not the website bucket: the site build would delete the logs) > Submit.

#Security headers

Optional. The site build sets Cache-Control and Content-Type only; it sets no security headers, and nothing in the code relies on them. If KIMS wants HSTS and the usual headers, attach a response headers policy to the default behaviour: the distribution > Behaviors > Default (*) > Edit > Response headers policy > the managed SecurityHeadersPolicy > Save changes. Read the headers it adds in the console first (it includes HSTS, which browsers then remember for the host). A Content-Security-Policy would need testing against the site's Google Tag Manager and maps first.

#Check it works

#Before the first build

bash
aws cloudfront get-distribution --id <DISTRIBUTION_ID> --query "Distribution.{status:Status,domain:DomainName,origin:DistributionConfig.Origins.Items[0].DomainName,oac:DistributionConfig.Origins.Items[0].OriginAccessControlId,root:DistributionConfig.DefaultRootObject,fn:DistributionConfig.DefaultCacheBehavior.FunctionAssociations.Items[0].FunctionARN,errors:DistributionConfig.CustomErrorResponses.Items[].ErrorCode}"
aws cloudfront describe-function --name kims-viewer-request --stage LIVE --query "FunctionSummary.{status:Status,runtime:FunctionConfig.Runtime,kvs:FunctionConfig.KeyValueStoreAssociations}"
bash
aws cloudfront get-distribution --id <DISTRIBUTION_ID> --query "Distribution.{status:Status,domain:DomainName,origin:DistributionConfig.Origins.Items[0].DomainName,oac:DistributionConfig.Origins.Items[0].OriginAccessControlId,root:DistributionConfig.DefaultRootObject,fn:DistributionConfig.DefaultCacheBehavior.FunctionAssociations.Items[0].FunctionARN,errors:DistributionConfig.CustomErrorResponses.Items[].ErrorCode}"
aws cloudfront describe-function --name kims-viewer-request --stage LIVE --query "FunctionSummary.{status:Status,runtime:FunctionConfig.Runtime,kvs:FunctionConfig.KeyValueStoreAssociations}"
powershell
aws cloudfront get-distribution --id <DISTRIBUTION_ID> --query "Distribution.{status:Status,domain:DomainName,origin:DistributionConfig.Origins.Items[0].DomainName,oac:DistributionConfig.Origins.Items[0].OriginAccessControlId,root:DistributionConfig.DefaultRootObject,fn:DistributionConfig.DefaultCacheBehavior.FunctionAssociations.Items[0].FunctionARN,errors:DistributionConfig.CustomErrorResponses.Items[].ErrorCode}"
aws cloudfront describe-function --name kims-viewer-request --stage LIVE --query "FunctionSummary.{status:Status,runtime:FunctionConfig.Runtime,kvs:FunctionConfig.KeyValueStoreAssociations}"

You should see Deployed, the d....cloudfront.net domain, the bucket's REST address (.s3.<REGION>.amazonaws.com), an OAC id, index.html, the function ARN, [403, 404]; then UNASSOCIATED or DEPLOYED, cloudfront-js-2.0, and null for the store on the first day.

#After the first site build

Use d....cloudfront.net until the website host's DNS points here.

bash
SITE=https://<DISTRIBUTION_DOMAIN_OR_SITE_HOST>
for path in / /bengaluru/doctors/ /bengaluru/doctors /kn/ /sitemap.xml /robots.txt /no-such-page/; do
  printf '%-22s ' "$path"; curl -s -o /dev/null -w '%{http_code}  %{content_type}\n' "$SITE$path"
done
curl -sI "$SITE/bengaluru/doctors/" | grep -iE '^(cache-control|x-cache|content-encoding)'
curl -s -o /dev/null -w 'direct S3: %{http_code}\n' "https://<WEBSITE_BUCKET>.s3.<REGION>.amazonaws.com/index.html"
bash
SITE=https://<DISTRIBUTION_DOMAIN_OR_SITE_HOST>
for path in / /bengaluru/doctors/ /bengaluru/doctors /kn/ /sitemap.xml /robots.txt /no-such-page/; do
  printf '%-22s ' "$path"; curl -s -o /dev/null -w '%{http_code}  %{content_type}\n' "$SITE$path"
done
curl -sI "$SITE/bengaluru/doctors/" | grep -iE '^(cache-control|x-cache|content-encoding)'
curl -s -o /dev/null -w 'direct S3: %{http_code}\n' "https://<WEBSITE_BUCKET>.s3.<REGION>.amazonaws.com/index.html"
powershell
$Site = "https://<DISTRIBUTION_DOMAIN_OR_SITE_HOST>"
foreach ($path in "/", "/bengaluru/doctors/", "/bengaluru/doctors", "/kn/", "/sitemap.xml", "/robots.txt", "/no-such-page/") {
  "{0,-22} {1}" -f $path, (curl.exe -s -o NUL -w "%{http_code}  %{content_type}" "$Site$path")
}
curl.exe -sI "$Site/bengaluru/doctors/" | Select-String -Pattern '^(cache-control|x-cache|content-encoding)'
curl.exe -s -o NUL -w "direct S3: %{http_code}" "https://<WEBSITE_BUCKET>.s3.<REGION>.amazonaws.com/index.html"
Path Expected
/ 200 text/html; charset=utf-8
/bengaluru/doctors/ 200 text/html (if 404 or 403 here while / works, the function is not attached)
/bengaluru/doctors 200 text/html (the function adds /index.html)
/kn/ 200 text/html
/sitemap.xml 200 application/xml
/robots.txt 200 text/plain: production allows search engines, UAT disallows all
/no-such-page/ 404 text/html (the site's own 404 page)
Headers of a page cache-control: no-cache, must-revalidate, x-cache: Miss from cloudfront or Hit from cloudfront (or RefreshHit), content-encoding: br or gzip
Direct S3 403: the bucket is private

#If it goes wrong

What you see Likely cause What to do
Home page works, every other page is 403 or the 404 page The function is not published, or not on the default behaviour Associate the function; check describe-function --stage LIVE
Every request fails with a 503 or The CloudFront function associated with the CloudFront distribution is invalid or could not run viewer-request-redirects.js published with no KeyValueStore, or a syntax the runtime rejects Put viewer-request.js back and publish, then follow Redirects KeyValueStore in order
Every request is 403 AccessDenied, the home page too Bucket policy missing or names another distribution, or the origin uses an OAI or no OAC The website bucket policy; the origin must show an OAC id
XML <Error><Code>AccessDenied shown to visitors No custom error responses Add 403 and 404 to /404.html with code 404
/no-such-page/ returns 200 with the home page Error responses point at /index.html with 200 (single-page-app style) Change them to /404.html, code 404
Origin shows ...s3-website... The website endpoint was chosen Edit the origin to <WEBSITE_BUCKET>.s3.<REGION>.amazonaws.com with OAC
CNAMEAlreadyExists The host is on another distribution (the old site) Alternate domain name and certificate
InvalidViewerCertificate Certificate not in us-east-1, not Issued, or does not cover the host Certificates
The site shows old pages after a build Invalidation skipped or failed Check CLOUDFRONT_DISTRIBUTION_ID and AWS_REGION in kims-site-env; the build's Invalidate stage; invalidate by hand
An old URL is 404, not 301 No store, store not associated, build skipped Redirects, or a different store in KIMS_REDIRECTS_KVS_ARN Compare describe-function store ARN with the job's; list-keys
test-function: PreconditionFailed The ETag is stale Read it again with describe-function --stage DEVELOPMENT
update-distribution: IllegalUpdate or InvalidArgument on Windows JSON flattened by ConvertTo-Json Keep -Depth 50

#Sources

Built 2026-11-29. Commands are shown for the system picked at the top; every block has all three.