本节介绍以S3作为源时,如何配置CORS - 跨源资源共享
。首先要在S3上配置CORS,再在CloudFront上加上相应头部。
CORS 是一项 HTTP 功能,它使用标头允许浏览器显示 Web 服务器从其他来源请求的内容。如果向未配置CORS的S3发出跨源请求,则不会返回 CORS 标头。
例如:
curl -i http://mycorsbucket.s3.amazonaws.com/cors-test.html -H "Origin: http://www.example.com"
HTTP/1.1 200 OK
x-amz-id-2: Va106gWx1uUDGbouopXfpjvjHW0VXydI8/VGlraf/62f2vvxtI+iAnmu7lF4MK2B6CxuzReyfRI=
x-amz-request-id: QWNNX1Y0MWFM152H
Date: Thu, 04 Nov 2021 18:52:55 GMT
Last-Modified: Thu, 04 Nov 2021 16:03:50 GMT
ETag: "cd4276d2cd5a2dc8ebcc1e04746680f6"
Accept-Ranges: bytes
Content-Type: text/html
Server: AmazonS3
Content-Length: 55
打开S3, 进入 Permissions (权限),在跨源资源共享中,选择编辑。输入 JSON CORS 规则:
Example:
[
{
"AllowedHeaders": [
"Authorization"
],
"AllowedMethods": [
"GET",
"HEAD"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"Access-Control-Allow-Origin"
]
}
]
有关每个 CORS 规则或示例的更多信息,请参阅 CORS 配置 。选择保存。
要使用 AWS CLI 在存储桶上配置 CORS 规则,请运行以下命令:
aws s3api put-bucket-cors --bucket mycorsbucket --cors-configuration '{"CORSRules" : [{"AllowedHeaders":["Authorization"],"AllowedMethods":["GET","HEAD"],"AllowedOrigins":["http://www.example.com"],"ExposeHeaders":["Access-Control-Allow-Origin"]}]}'
要测试 CORS 规则,请使用 cURL 命令,如下所示:
curl -i http://mycorsbucket.s3.amazonaws.com/index.html -H "Origin: http://www.example.com"
HTTP/1.1 200 OK
x-amz-id-2: d5Jsw1vCf8tR3cMdXrtcTKYgczU/1pjxahnrw7C6jU1fLo8py2Nv2kpeFs8pYPruVZg6Y3JuRUA=
x-amz-request-id: BMCCY18E58B3GBWV
Date: Thu, 04 Nov 2021 19:12:26 GMT
Access-Control-Allow-Origin: http://www.example.com
Access-Control-Allow-Methods: GET, HEAD
Access-Control-Expose-Headers: Access-Control-Allow-Origin
Access-Control-Allow-Credentials: true
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
Last-Modified: Thu, 04 Nov 2021 16:03:50 GMT
ETag: "cd4276d2cd5a2dc8ebcc1e04746680f6"
Accept-Ranges: bytes
Content-Type: text/html
Server: AmazonS3
Content-Length: 55
如果 CORS 规则配置正确,您将收到 200 OK 响应。
实际测试这一步不用配置也可以。
如果源是 S3 存储桶,则配置CloudFront以将以下标头转发到 S3:
测试:
参考: