# CORS settings

> Configure cross-origin rules for a bucket so scripts on specified websites can read or upload files, and learn about the HTTP/3 switch.

When a web script requests a resource from another domain, the browser checks the cross-origin (CORS) response headers. You use the settings here when you need to upload files from a web page with a script, read JSON, load fonts, or use images in a canvas.

To get there, go to **Object Storage (对象存储) › [Bucket list (桶列表)](https://console.bitiful.com/buckets)** › click the bucket name › **Access management (访问管理) › CORS configuration (跨域配置)**.

## Default behavior

| State             | Effect                                                                                                  |
| :---------------- | ------------------------------------------------------------------------------------------------------- |
| No rules          | All origins, methods, and request headers are allowed (`Access-Control-Allow-Origin: *`)                |
| At least one rule | Only requests that match a rule get CORS response headers, and other origins are blocked by the browser |

Most scenarios therefore need no configuration. Add rules when you need to restrict origins.

> **Info**
>
> CORS is enforced by the browser and affects only web scripts. It can't prevent hotlinking or downloads. To restrict access, use [access control](https://docs.bitiful.com/en/bitiful-s4/handbook/anti-leech.md).
>
> When you access through a CDN domain, configure CORS response headers in the [CDN settings](https://docs.bitiful.com/en/cdn/handbook/performance.md).

## Add a rule

### Create a rule

Click **New rule (新建规则)**.

### Fill it in

Fill in each field as described below.

### Save

Click **Save (保存)**, and it takes effect immediately. The browser may still use an old preflight cache, so verify in an incognito window.

- `Origins` (multiline text, required): The allowed websites, one per line, with at most one `*` per line. Write it as `https://www.example.com`, without a trailing `/`. If you omit the protocol, both http and https match. Enter `*` for all origins. Up to 10 per rule.

- `Allowed Methods` (multiple choice, required): `GET`, `POST`, `PUT`, `DELETE`, `HEAD`. Use GET and HEAD for reading, and PUT for presigned uploads.

- `Allowed Headers` (multiline text): Request headers that are allowed, one per line, case-insensitive. Enter `*` for all. Up to 10 per rule.

- `Exposed Headers` (multiline text): Response headers that web scripts are allowed to read, one per line, for example `ETag`. Up to 10 per rule.

- `Cache time (seconds)` (integer, default: 0): How long the browser caches the preflight result. 0 means no caching. `600` is common.

> **Info**
>
> Preflight (`OPTIONS`) requests are currently always allowed, and the rules apply to the response of the actual request: if the origin or method doesn't match, the response carries no CORS headers and the browser doesn't hand the result to the script. Write requests (such as a presigned PUT) may already have been executed, so don't use CORS as access control.

Each bucket can have up to 10 rules. With multiple rules, S4 goes through the table from top to bottom and uses the first rule that matches.

Use **Edit (编辑)** to modify and **Delete (删除)** to remove. After you delete the last rule, the bucket returns to the default of allowing everything.

## How to write origins

| Format                    | Matches                                                   | Doesn't match            |
| :------------------------ | --------------------------------------------------------- | ------------------------ |
| `https://www.example.com` | `https://www.example.com`                                 | `http://www.example.com` |
| `www.example.com`         | `www.example.com` beginning with `http://` and `https://` | `example.com`            |
| `https://*.example.com`   | `https://a.example.com`                                   | `https://example.com`    |
| `http://localhost:*`      | `http://localhost:3000` and any other port                | `http://127.0.0.1:3000`  |
| `*`                       | Everything                                                | None                     |

If an origin includes a port, the port must match too.

## Typical configurations

**Web presigned upload**

| Item                 | Value                     |
| :------------------- | ------------------------- |
| Origins              | `https://www.example.com` |
| Allowed Methods      | PUT, GET, HEAD            |
| Allowed Headers      | `*`                       |
| Exposed Headers      | `ETag`                    |
| Cache time (seconds) | `600`                     |

**Public fonts and JSON**

| Item                 | Value            |
| :------------------- | ---------------- |
| Origins              | `*`              |
| Allowed Methods      | GET, HEAD        |
| Allowed Headers      | `*`              |
| Exposed Headers      | `Content-Length` |
| Cache time (seconds) | `3600`           |

**Local development**

| Item                 | Value                        |
| :------------------- | ---------------------------- |
| Origins              | `http://localhost:*`         |
| Allowed Methods      | GET, PUT, POST, DELETE, HEAD |
| Allowed Headers      | `*`                          |
| Exposed Headers      | `ETag`                       |
| Cache time (seconds) | `0`                          |

## Verify

```bash
curl -s -o /dev/null -D - "https://my-bucket.s3.bitiful.net/test.txt" \
  -H "Origin: https://www.example.com"
```

If `access-control-allow-origin: https://www.example.com` appears in the response, the rule matched (the rule must include GET).

## Set with the S3 API

You can also manage CORS with the S3 PutBucketCors, GetBucketCors, and DeleteBucketCors operations. A sub-user needs write permission on the whole bucket (and read permission to read).

```bash
aws s3api put-bucket-cors --bucket my-bucket \
  --endpoint-url https://s3.bitiful.net --region cn-east-1 \
  --cors-configuration '{
    "CORSRules": [{
      "AllowedOrigins": ["https://www.example.com"],
      "AllowedMethods": ["GET", "PUT", "HEAD"],
      "AllowedHeaders": ["*"],
      "ExposeHeaders": ["ETag"],
      "MaxAgeSeconds": 600
    }]
  }'
```

> **Warning**
>
> PutBucketCors replaces all existing rules in the bucket.

## Enable HTTP/3

The **Enable HTTP/3 (启用HTTP/3)** switch on the same page tells clients they can use the QUIC protocol to access this bucket, which reduces connection time on weak networks.

- When it's on, responses carry an `Alt-Svc` declaration. Clients cache it for 7 days and then try HTTP/3 on later requests, falling back to HTTP/2 automatically when it isn't supported.
- It applies only when you access the bucket through your own domain, and doesn't affect CDN domains. For CDN HTTP/3, see [HTTPS settings](https://docs.bitiful.com/en/cdn/handbook/https.md).
- After you turn it off, clients that already received the declaration may keep trying HTTP/3 until their cache expires.

The switch saves immediately when you toggle it, so you don't need to click Save.

## FAQ

<details>
<summary>After I added a rule, a site that used to work reports a CORS error</summary>

After you add the first rule, origins not listed are no longer allowed. Add every site you need to the rules, or delete all rules.

</details>

<details>
<summary>I configured it but still get No 'Access-Control-Allow-Origin'</summary>

1. The origin has a trailing `/`, or the protocol or port doesn't match.
2. The request's method isn't selected.
3. You're using a CDN domain, which needs to be configured on the CDN.

</details>

<details>
<summary>I see CORSTooManyRules or CORSRuleTooManyDomains</summary>

You exceeded the limit of 10 rules per bucket, or 10 origins and headers per rule. Merge them with `*` wildcards.

</details>
