背景
CloudFrontの設定画面には、以下のようなobject cachingに関する欄が存在する。
Select Use Origin Cache Headers if your origin server is adding a Cache-Control header to control how long your objects stay in the CloudFront cache. Select Customize to specify a minimum time that objects stay in the CloudFront cache regardless of Cache-Control headers.
Origin server (今回はS3) が Cache-Control
headerを利用してCloudFrontのcacheの保持期間を制御する場合は、Origin cache headerを選択し、 Cache-Control
headerに関係無くCloudFrontのcache時間を制御するには Customize
を選択しろとのこと。
今回実現したいことは、CloudFrontにはcacheさせず常に200 statusでclient側へ静的objectを返したい。つまりcacheさせたくない。
前提
- S3 Bucketとobjectを作成。
- S3 Web static hostingは設定しない。
- AWS CloudFront distributionを作成し、originに当該S3とPATHを指定。
Pattern 1. Use Origin Cache Headers
を選択し、Cache-Controlは設定しない
- CloudFrontのTTL設定: 無し
object caching
:Use Origin Cache Headers
- S3 objectのCache-Control: 無し
CloudFrontのdomain経由でS3 objectへリクエストすると 304 Not Modified
が返る。
Origin Server (S3) がCache-Control headerを持っていない為、CloudFrontのcacheが効いていると思われる。
Pattern 2. Use Origin Cache Headers
を選択しCache-Controlを設定する
- CloudFrontのTTL設定: 無し
- object caching:
Use Origin Cache Headers
- S3 objectのCache-Control:
no-cache, no-store, must-revalidate
を設定
常に200 statusが返る。
Pattern 3. Customize
を選択し、CloudFrontのTTLで全て0を指定する
- CloudFrontのTTL: 全て0
object caching
:Customize
- S3 objectのCache-Control: 無し
CloudFrontデフォルトのTTL設定は次の通り。
- min_ttl = 0
- default_ttl = 3600
- max_ttl = 86400
上記全てTTL関連の設定を0にして、S3 objectにおけるMetadataのCache-Controlを消してリクエストしたところ、304と200 statusが交互にresponseされるようになった (この挙動は予想していなかった)。
Summary
TTLの期限が切れた場合Originは304 Not modifiedのレスポンスを返す可能性があるのと、TTL: 0を指定していても304が返る可能性がある為、200 statusで返したい場合は当該オブジェクトに Cache-Control: no-cache, no-store, must-revalidate
を設定し、 Customize
ではなく Use Origin Cache Headers
を選択する。
Cache-Control: max-age=0
- response contentsが最新であればcacheを返すのを許可する。
Cache-Control: no-cache
- Origin serverに一度確認してからcacheを利用する。
- 初回cache時にserverからのresponse header (Etag) を記憶する。
- Etag headerの内容を
If-None-Match
headerに入れてrequestし304 response statusの場合はcacheから読み込む。
- browserのsuper reload時のrequest時に指定される。
no-cache
はcacheの利用を暗に許可している。
- Origin serverに一度確認してからcacheを利用する。
Cache-Control: no-store
- caheの利用を許可しない。
CloudFrontの仕様
- 多くの場合、動的コンテンツはcacheできないか、非常に短い期間 (数秒) cache可能。
- 古くは全コンテンツが静的objectであると見なされていたためCloudFrontの最小TTLは60分だった。
- 新しい最小TTL値は0秒。
- 特定originのTTLを0に設定しても、CloudFrontはそのoriginのcontentsをcacheする。