Skip to main content

Cloud and deployment · Intermediate · 18 min

Cache content well on CloudFront and invalidate it when you deploy

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4

You will have a deploy script that uploads a static site to S3 with the right Cache-Control header for each kind of file, a CloudFront distribution using managed cache and security header policies, and invalidations that cover only the files that really changed.

On this page

The static site tutorial left you with a working distribution that caches everything for the same 24 hours, whatever the file. That is wrong in both directions. Your CSS and JavaScript could be cached for a year, because their content never changes under the same name, while your HTML should be checked on every visit, so a deploy shows up straight away. When people get this wrong, they end up running create-invalidation --paths "/*" after every deploy and hoping.

In this tutorial you give each kind of file its own Cache-Control header, so most deploys need no invalidation at all. You will:

  • build a small site whose CSS and JS files carry a content hash in their names (app.3f9c1a2b.css);
  • write a deploy script that uploads hashed files as cacheable for a year, other files for a day, and HTML with no-cache;
  • attach CloudFront's managed cache policy and its managed security headers policy to the distribution;
  • read the x-cache and age headers to see the cache at work;
  • ship a change and let the script invalidate only the plain-named files whose content changed.

Your working files live in ~/cf-cache-demo. Nothing here creates a new billable resource, but requests, data transfer and invalidations beyond the free allowance are billed on the distribution you already have. Check aws.amazon.com/cloudfront/pricing/ for current prices.

Step 1 · Pick up your bucket and distribution

You need version 2 of the AWS CLI and jq. If aws --version already prints aws-cli/2.42 or later, skip the install part. Otherwise install 2.42.4 from Amazon's versioned installer, as in the S3 tutorials:

Bash
sudo apt update
sudo apt install -y curl unzip jq ca-certificates
AWS_CLI_VERSION=2.42.4
cd "$(mktemp -d)"
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install --update
aws --version

The CLI does not get updates from apt. To upgrade later, run the same commands with a newer version number. The zip is large, so on prepaid mobile data download it once over Wi-Fi and keep it.

Now find your bucket and distribution again. The static site tutorial named the bucket after your account number and gave the distribution the comment Static site for <bucket>, so both can be looked up. Use the Region you used there (eu-west-1 was its example). If you use a named profile, run export AWS_PROFILE=<your-profile> first (replace the placeholder):

Bash
mkdir -p ~/cf-cache-demo
cd ~/cf-cache-demo
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
DIST_ID=$(aws cloudfront list-distributions \
  --query "DistributionList.Items[?Comment=='Static site for my-site-${ACCOUNT_ID}-demo'].Id | [0]" \
  --output text)
DIST_DOMAIN=$(aws cloudfront get-distribution --id "$DIST_ID" \
  --query Distribution.DomainName --output text)
cat > demo.env <<EOF
export AWS_REGION=eu-west-1
export BUCKET=my-site-${ACCOUNT_ID}-demo
export DIST_ID=${DIST_ID}
export DIST_DOMAIN=${DIST_DOMAIN}
EOF
. ./demo.env
cat demo.env

demo.env keeps the four values, so a new terminal can load them with cd ~/cf-cache-demo && . ./demo.env.

Check it worked

demo.env shows a bucket name, a distribution ID of capital letters and digits, and an address ending in .cloudfront.net. If DIST_ID is None, the comment did not match: run aws cloudfront list-distributions --query 'DistributionList.Items[].[Id,Comment]' --output text and copy the right ID into demo.env by hand.

Step 2 · Build a site with content hashes in the asset names

The trick that makes long caching safe is to change a file's name whenever its content changes. Build tools such as Vite, webpack and Hugo Pipes already do this: they write dist/assets/index-BX3k9a.js and point the HTML at that name. A browser or CDN that cached the old name is not wrong, because nobody asks for the old name any more.

To keep this tutorial free of a framework, a short script stands in for your build tool. Create the source files first:

Bash
cd ~/cf-cache-demo
mkdir -p src
cat > src/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Cache demo</title>
  <link rel="stylesheet" href="@CSS@">
</head>
<body>
  <h1>Cache demo</h1>
  <p id="status">Loading...</p>
  <script src="@JS@" defer></script>
</body>
</html>
HTML
cat > src/app.css <<'CSS'
body { font-family: system-ui, sans-serif; max-width: 40rem; margin: 2rem auto; padding: 0 1rem; }
h1 { color: #1f2933; }
CSS
cat > src/app.js <<'JS'
document.getElementById('status').textContent = 'Scripts load from a hashed file name.';
JS
cat > src/robots.txt <<'TXT'
User-agent: *
Allow: /
TXT

Then the build script. It takes the first eight characters of each file's SHA-256 hash, copies the file to dist/assets/ under the hashed name, and writes those names into the HTML:

Bash
cd ~/cf-cache-demo
cat > build.sh <<'SH'
#!/usr/bin/env bash
# Stand-in for a real build tool: hashed CSS and JS names, HTML pointing at them.
set -euo pipefail
cd "$(dirname "$0")"
rm -rf dist
mkdir -p dist/assets
css_hash=$(sha256sum src/app.css | cut -c1-8)
js_hash=$(sha256sum src/app.js | cut -c1-8)
cp src/app.css "dist/assets/app.${css_hash}.css"
cp src/app.js "dist/assets/app.${js_hash}.js"
sed -e "s|@CSS@|/assets/app.${css_hash}.css|" \
    -e "s|@JS@|/assets/app.${js_hash}.js|" src/index.html > dist/index.html
cp src/robots.txt dist/robots.txt
(cd dist && find . -type f | sort)
SH
chmod +x build.sh
./build.sh

Check it worked

The script lists four files: ./assets/app.<8 characters>.css, ./assets/app.<8 characters>.js, ./index.html and ./robots.txt. grep -o '/assets/[^"]*' dist/index.html prints the same two hashed names. Run ./build.sh again without changing anything and the names stay the same; edit src/app.css and the CSS name changes.

Step 3 · Upload each kind of file with its own Cache-Control

Cache-Control is stored on each S3 object as metadata, and S3 sends it with the file. CloudFront and browsers both read it. Three rules cover a static site:

  • Hashed files under assets/: public, max-age=31536000, immutable. One year, and immutable tells browsers not to recheck the file even when the visitor reloads the page. With the CachingOptimized policy, CloudFront also keeps them for up to a year, its maximum TTL.
  • HTML files: no-cache. Despite the name, this means "store it, but check with the server before using it". Browsers ask CloudFront every time, and the answer is often a small 304 Not Modified. CloudFront's CachingOptimized policy has a minimum TTL of 1 second, and AWS documents that a minimum above 0 wins over no-cache, so the edge keeps your HTML for about a second before it checks S3 again.
  • Everything else with a plain name (robots.txt, favicon.ico, a social preview image): public, max-age=86400, one day. These are the only files you ever need to invalidate.

This split matters most for visitors on slow or prepaid mobile connections, which describes much of the audience in many African countries: on a repeat visit the browser downloads only the small HTML file and reuses the CSS, JavaScript and fonts it already has.

The upload order matters too. Upload the new hashed assets first, other files next, and HTML last. If the HTML went first, someone could load a page that points at a CSS file that is not there yet. Never delete the old hashed files during a deploy: a visitor with the previous page open still needs them.

The script also works out what to invalidate. Before it uploads anything, it lists the ETag of every object already in the bucket. For a file uploaded in one part without SSE-KMS encryption, the ETag is the file's MD5 hash, so comparing it with md5sum of the local file shows which plain-named files really changed. A rebuilt robots.txt with the same content is not invalidated:

Bash
cd ~/cf-cache-demo
cat > deploy.sh <<'SH'
#!/usr/bin/env bash
# Upload dist/ with a Cache-Control header per kind of file, then invalidate
# only the plain-named, non-HTML files whose content changed.
set -euo pipefail
: "${BUCKET:?Run . ./demo.env first}"
: "${DIST_ID:?Run . ./demo.env first}"
cd "$(dirname "$0")/dist"
rm -f ../last-invalidation.txt

# 1. What is in the bucket now: key and ETag (the MD5 for single-part uploads).
aws s3api list-objects-v2 --bucket "$BUCKET" \
  --query 'Contents[].[Key,ETag]' --output text | tr -d '"' > ../remote.tsv

# 2. Plain-named files that already exist in the bucket with different content.
changed=()
while IFS= read -r key; do
  local_md5=$(md5sum "$key" | cut -d' ' -f1)
  remote_md5=$(awk -F'\t' -v k="$key" '$1 == k { print $2 }' ../remote.tsv)
  if [ -n "$remote_md5" ] && [ "$remote_md5" != "$local_md5" ]; then
    changed+=("/$key")
  fi
done < <(find . -type f ! -path './assets/*' ! -name '*.html' | sed 's|^\./||' | sort)

# 3. Upload: hashed assets first, other files next, HTML last.
aws s3 sync assets "s3://$BUCKET/assets" \
  --cache-control 'public, max-age=31536000, immutable'
aws s3 sync . "s3://$BUCKET" --exclude 'assets/*' --exclude '*.html' \
  --cache-control 'public, max-age=86400'
aws s3 cp . "s3://$BUCKET" --recursive --exclude '*' --include '*.html' \
  --cache-control 'no-cache'

# 4. Invalidate only what changed.
if [ "${#changed[@]}" -eq 0 ]; then
  echo "Nothing to invalidate"
else
  inv_id=$(aws cloudfront create-invalidation --distribution-id "$DIST_ID" \
    --paths "${changed[@]}" --query 'Invalidation.Id' --output text)
  echo "$inv_id" > ../last-invalidation.txt
  echo "Invalidation $inv_id for: ${changed[*]}"
fi
SH
chmod +x deploy.sh
./deploy.sh

Three limits to know about. aws s3 uploads files of 8 MB or more in parts, and S3 encrypted with SSE-KMS does not use MD5 for ETags; either way such a file always looks changed and gets invalidated, which costs a path but does no harm. File names with spaces or non-ASCII characters must be URL-encoded in invalidation paths, so keep plain-named files to simple ASCII names. And sync without --delete never removes files from the bucket; the last step tidies old assets on purpose.

Check it worked

The first run uploads four files and prints Nothing to invalidate, because robots.txt was new and the HTML is no-cache. Read the header S3 stored on each kind of file:

Bash
cd ~/cf-cache-demo
CSS_KEY="assets/$(ls dist/assets | grep '\.css$')"
for key in index.html robots.txt "$CSS_KEY"; do
  printf '%-28s %s\n' "$key" "$(aws s3api head-object --bucket "$BUCKET" --key "$key" \
    --query CacheControl --output text)"
done

index.html shows no-cache, robots.txt shows public, max-age=86400, and the CSS file shows public, max-age=31536000, immutable.

Step 4 · Choose the cache, origin request and response headers policies

A CloudFront cache behaviour takes up to three policies, each by ID:

  • The cache policy sets the minimum, default and maximum TTL and what goes into the cache key. Keep the managed CachingOptimized policy (658327ea-f89d-4fab-a63d-7e88639e58f6). Its key holds only the path and the normalised Accept-Encoding header, with no cookies or query strings, so every visitor shares one cached copy. Its TTLs are 1 second minimum, 24 hours default (for files without Cache-Control) and 365 days maximum, and your headers choose within that range. Two other managed policies are worth knowing: CachingDisabled (4135ea2d-6df8-44a3-9df3-4b5a84be39ad) for paths that must never be cached, and UseOriginCacheControlHeaders, whose minimum TTL is 0 but which also puts Host, Origin and all cookies in the cache key, which lowers your hit rate on a static site.
  • The origin request policy adds values to the request CloudFront sends to S3 without putting them in the cache key. A bucket of static files needs none, so leave it unset. Add the managed CORS-S3Origin policy (88a5eaf4-2fd4-4709-b370-b4c650ea3fcf) only if another site loads your fonts or files and the bucket has a CORS configuration. The AllViewer policies forward every header, cookie and query string, which a bucket has no use for.
  • The response headers policy adds headers to what CloudFront sends to browsers. The managed SecurityHeadersPolicy (67f7725c-6f97-4210-82d7-5512b31e9d03) adds Strict-Transport-Security: max-age=31536000, X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN, Referrer-Policy: strict-origin-when-cross-origin and X-XSS-Protection: 1; mode=block. It always sets X-Content-Type-Options; for the other four, a header that already comes from S3 wins.

Changing a distribution means reading its whole configuration and the ETag that proves you read the latest version, editing it, and sending it all back. jq sets the two policy IDs and removes any origin request policy:

Bash
cd ~/cf-cache-demo
ETAG=$(aws cloudfront get-distribution-config --id "$DIST_ID" --query ETag --output text)
aws cloudfront get-distribution-config --id "$DIST_ID" \
  --query DistributionConfig --output json \
  | jq --arg cache 658327ea-f89d-4fab-a63d-7e88639e58f6 \
       --arg headers 67f7725c-6f97-4210-82d7-5512b31e9d03 \
       '.DefaultCacheBehavior.CachePolicyId = $cache
        | .DefaultCacheBehavior.ResponseHeadersPolicyId = $headers
        | del(.DefaultCacheBehavior.OriginRequestPolicyId)' \
  > distribution-policies.json
aws cloudfront update-distribution --id "$DIST_ID" --if-match "$ETAG" \
  --distribution-config file://distribution-policies.json \
  --query Distribution.Status --output text
aws cloudfront wait distribution-deployed --id "$DIST_ID"

update-distribution prints InProgress, and the wait returns once every edge location has the new settings, which can take several minutes. A PreconditionFailed error means someone changed the distribution after you read the ETag; run the block again.

The managed policy has no Content-Security-Policy, because a useful one depends on your site. When you have written one (/tutorials/add-security-headers-in-nginx explains the header), create your own response headers policy with it and use that policy's ID instead.

Check it worked

Bash
aws cloudfront get-distribution-config --id "$DIST_ID" \
  --query 'DistributionConfig.DefaultCacheBehavior.[CachePolicyId,ResponseHeadersPolicyId,OriginRequestPolicyId]' \
  --output text

It prints the CachingOptimized ID, the SecurityHeadersPolicy ID and None.

Step 5 · Read x-cache and age to see the cache work

CloudFront tells you what it did in two response headers. x-cache says whether the edge location had the file: Miss from cloudfront (it fetched the file from S3), Hit from cloudfront (served from its cache) or RefreshHit from cloudfront (its copy had expired, it checked S3, and S3 said the file had not changed). age is the number of seconds the response has been in the edge cache.

Request the hashed CSS file twice, a few seconds apart, and show only the headers that matter. -I sends a HEAD request, which CloudFront caches like a GET:

Bash
cd ~/cf-cache-demo
CSS_PATH="/assets/$(ls dist/assets | grep '\.css$')"
for i in 1 2; do
  curl -sI "https://$DIST_DOMAIN$CSS_PATH" \
    | grep -iE '^(x-cache|age|cache-control|strict-transport-security|x-content-type-options):'
  echo ---
  sleep 5
done
curl -sI "https://$DIST_DOMAIN/" | grep -iE '^(x-cache|age|cache-control):'

Each edge location has its own cache, so the first request from your city is usually a miss even if someone elsewhere already loaded the file. Sending Cache-Control: no-cache from curl or a browser does not make CloudFront go back to S3; it ignores that header in requests.

Check it worked

The first CSS request shows x-cache: Miss from cloudfront and no age. The second shows x-cache: Hit from cloudfront and an age of a few seconds. Both show cache-control: public, max-age=31536000, immutable, strict-transport-security: max-age=31536000 and x-content-type-options: nosniff. The request for / shows cache-control: no-cache, and x-cache is Miss or RefreshHit rather than a long-lived Hit. If every request is a miss, wait for the policy change to finish deploying, and check that the URL has no changing query string.

Step 6 · Ship a change and invalidate only what changed

Change the stylesheet, which gets a new hashed name, and robots.txt, which keeps its name:

Bash
cd ~/cf-cache-demo
cat > src/app.css <<'CSS'
body { font-family: system-ui, sans-serif; max-width: 40rem; margin: 2rem auto; padding: 0 1rem; }
h1 { color: #1f2933; letter-spacing: -0.01em; }
p { line-height: 1.6; }
CSS
cat > src/robots.txt <<'TXT'
User-agent: *
Allow: /
Disallow: /drafts/
TXT
./build.sh
./deploy.sh

The script uploads the new CSS file, robots.txt and index.html, and prints something like Invalidation I2J0I21PCUYOIK for: /robots.txt. The CSS needs no invalidation, because no one has ever requested its new name. index.html needs none either, because browsers revalidate it and the edge rechecks it within a second. Only robots.txt was cached under a name whose content changed.

Wait for the invalidation to finish and read back what it covered:

Bash
cd ~/cf-cache-demo
INV_ID=$(cat last-invalidation.txt)
aws cloudfront wait invalidation-completed --distribution-id "$DIST_ID" --id "$INV_ID"
aws cloudfront get-invalidation --distribution-id "$DIST_ID" --id "$INV_ID" \
  --query 'Invalidation.{Status: Status, Paths: InvalidationBatch.Paths.Items}' --output json

On cost: as checked on 26 November 2026, the first 1,000 invalidation paths each month are free for the whole AWS account, across all its distributions, and each path after that is billed. A wildcard such as "/*" counts as one path however many files it clears. Keep "/*" for emergencies, such as a file published by mistake. If your deploys invalidate everything every time, the cause is file names without hashes, and the fix is in your build, not in a bigger invalidation.

Check it worked

The JSON shows "Status": "Completed" and "Paths": ["/robots.txt"]. Run ./deploy.sh once more without changing anything: it prints Nothing to invalidate. curl -s "https://$DIST_DOMAIN/robots.txt" now includes the Disallow: /drafts/ line.

Step 7 · Remove old hashed files and clean up

Old hashed files pile up with every deploy. They cost little, but tidy them once nobody can still be using them. Because your HTML is no-cache, an old page lives only as long as someone keeps an old tab open, so a week after a deploy is a safe margin. Look at what would be removed first; --dryrun changes nothing:

Bash
cd ~/cf-cache-demo
aws s3 sync dist/assets "s3://$BUCKET/assets" --delete --dryrun \
  --cache-control 'public, max-age=31536000, immutable'

It prints one (dryrun) delete: line for the old CSS file. The next command deletes every file under assets/ in the bucket that is not in your current dist/assets, so run it only from a fresh build of the version that is live:

Bash
cd ~/cf-cache-demo
aws s3 sync dist/assets "s3://$BUCKET/assets" --delete \
  --cache-control 'public, max-age=31536000, immutable'

The managed policies belong to AWS, so there is nothing to delete for them. When you have finished with the site, run the "Delete everything" step of /tutorials/host-a-static-site-on-s3-and-cloudfront to remove the distribution, the access control and the bucket, then remove the local folder:

Bash
cd ~
rm -rf ~/cf-cache-demo

Check it worked

aws s3 ls "s3://$BUCKET/assets/" lists exactly one CSS and one JS file, the names in your current build. ls ~/cf-cache-demo reports that the folder does not exist.

Next steps

  • If you have not tidied up yet, the cleanup order for the distribution and bucket is in /tutorials/host-a-static-site-on-s3-and-cloudfront.
  • Write a Content-Security-Policy and the other security headers with /tutorials/add-security-headers-in-nginx, then move them into a custom CloudFront response headers policy.
  • Check what a site needs before any CDN sits in front of it with /tutorials/prepare-your-site-for-a-cdn.
  • Keep an eye on CloudFront and S3 charges with /tutorials/find-and-stop-what-is-costing-you-on-aws.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.