

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 AWS CLI 来配置 CORS
<a name="cors-configuration-cli"></a>

您可以通过 AWS CLI 使用 `--cors` 参数为您的 Lightsail 存储桶配置 CORS。该参数接受包含 CORS 配置的 JSON 文件。有关 CORS 配置元素的更多信息，请参阅 [CORS 配置的元素](cors-how-evaluation-works.md#cors-configuration-elements)。

**Topics**
+ [应用 CORS 配置](#cors-configuration-apply)
+ [示例 CORS 配置](#cors-configuration-examples)
+ [删除 CORS 配置](#cors-remove-configuration)

## 应用 CORS 配置
<a name="cors-configuration-apply"></a>

以下步骤说明了如何通过指定一个 Json 文件将 CORS 配置应用于存储桶。更多示例配置，请参阅 [示例 CORS 配置](#cors-configuration-examples)。

**要使用 AWS CLI 为存储桶配置 CORS**

1. 创建包含 CORS 配置的 JSON 文件。例如，创建一个名为 `cors-config.json` 的文件，其内容如下：

   ```
   {
     "CORSRules": [
       {
         "AllowedOrigins": ["https://example.com"],
         "AllowedMethods": ["GET", "PUT", "POST"],
         "AllowedHeaders": ["*"],
         "MaxAgeSeconds": 3000
       }
     ]
   }
   ```

1. 使用 AWS CLI 将 CORS 配置应用于您的存储桶：

   ```
   aws lightsail update-bucket --bucket-name {{amzn-s3-demo-bucket}} --cors file://{{cors-config.json}}
   ```

1. 验证 CORS 配置是否已成功应用：

   ```
   aws lightsail get-buckets --bucket-name {{amzn-s3-demo-bucket}} --include-cors
   ```

**注意**  
将 {{amzn-s3-demo-bucket}} 替换为您的 Lightsail 存储桶的名称。

## 示例 CORS 配置
<a name="cors-configuration-examples"></a>

以下示例介绍了不同使用场景中常见的 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 配置
<a name="cors-remove-configuration"></a>

要从您的存储桶删除 CORS 配置，请使用以下 AWS CLI 命令：

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

**注意**  
将 {{amzn-s3-demo-bucket}} 替换为您的 Lightsail 存储桶的名称。

删除 CORS 配置后，浏览器将阻止对您的存储桶的跨源请求。