使用 設定 CORS AWS CLI - Amazon Lightsail

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 設定 CORS AWS CLI

您可以使用 AWS CLI 搭配 --cors 參數來設定儲存Lightsail貯體的 CORS。此參數接受包含 CORS 組態的 JSON 檔案。如需 CORS 組態元素的詳細資訊,請參閱 CORS 組態的元素

套用 CORS 組態

下列程序顯示如何透過指定 JSON 檔案,將 CORS 組態套用至儲存貯體。如需更多範例組態,請參閱 CORS 組態範例

使用 設定儲存貯體的 CORS AWS CLI
  1. 建立包含 CORS 組態的 JSON 檔案。例如,cors-config.json使用下列內容建立名為 的檔案:

    { "CORSRules": [ { "AllowedOrigins": ["https://example.com"], "AllowedMethods": ["GET", "PUT", "POST"], "AllowedHeaders": ["*"], "MaxAgeSeconds": 3000 } ] }
  2. 使用 AWS CLI 將 CORS 組態套用至您的儲存貯體:

    aws lightsail update-bucket --bucket-name amzn-s3-demo-bucket --cors file://cors-config.json
  3. 確認 CORS 組態已成功套用:

    aws lightsail get-buckets --bucket-name amzn-s3-demo-bucket --include-cors
注意

amzn-s3-demo-bucket 取代為您的Lightsail儲存貯體名稱。

CORS 組態範例

下列範例顯示不同使用案例的常見 CORS 組態。

範例 1:允許所有原始伺服器和方法

此組態允許所有原始伺服器使用任何 HTTP 方法存取您的儲存貯體:

{ "CORSRules": [ { "AllowedOrigins": ["*"], "AllowedMethods": ["GET", "PUT", "POST", "DELETE", "HEAD"], "AllowedHeaders": ["*"], "MaxAgeSeconds": 3000 } ] }
範例 2:限制為特定網域

此組態僅允許來自 的請求https://mywebsite.com

{ "CORSRules": [ { "AllowedOrigins": ["https://mywebsite.com"], "AllowedMethods": ["GET", "PUT"], "AllowedHeaders": ["Authorization", "Content-Type"], "ExposeHeaders": ["ETag"], "MaxAgeSeconds": 3600 } ] }
範例 3:不同原始伺服器的多個規則

此組態會為不同的原始伺服器定義不同的規則:

{ "CORSRules": [ { "AllowedOrigins": ["https://mywebsite.com"], "AllowedMethods": ["GET", "PUT", "POST"], "AllowedHeaders": ["*"], "MaxAgeSeconds": 3600 }, { "AllowedOrigins": ["https://cdn.mywebsite.com"], "AllowedMethods": ["GET"], "AllowedHeaders": ["Authorization"], "MaxAgeSeconds": 86400 } ] }

移除 CORS 組態

若要從儲存貯體中移除 CORS 組態,請使用下列 AWS CLI 命令:

aws lightsail update-bucket --bucket-name amzn-s3-demo-bucket --cors '{"rules":[]}'
注意

amzn-s3-demo-bucket 取代為您的Lightsail儲存貯體名稱。

移除 CORS 組態後,瀏覽器會封鎖對儲存貯體的跨來源請求。