S3 + CloudFront の CORS 設定

手順をメモっとく

S3 の設定

[Permissions] > [CORS configuration] から以下のように設定を追加:

<CORSConfiguration>
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>

CloudFront の設定

[Behavior] > [Cache Based on Selected Request Headers] から Origin ヘッダだけをS3に通す設定を行う:

f:id:uraway:20181128231949p:plain

で、最後に curl で確認して、access-control-allow-origin: * が返ってきていればよし

$ curl -X GET -I -H "Origin: https://example.com" https://example.cloundfront.net/path/to/image.png
HTTP/2 200 
content-type: image/png
content-length: 43881
date: Wed, 28 Nov 2018 14:24:17 GMT
access-control-allow-origin: *
access-control-allow-methods: GET
last-modified: Mon, 30 Oct 2017 07:22:28 GMT
etag: ""
accept-ranges: bytes
server: AmazonS3
vary: Origin
x-cache: Miss from cloudfront