# Origin settings

> Set an S4 bucket or a custom origin, and change the origin address, origin Host header, origin path prefix, and origin request headers.

When the edge has no cached copy, the CDN fetches the file from your origin. This is called origin fetch. The origin determines where the CDN fetches from, and the origin settings determine which path to use and which request headers to send.

| Setting                                        | Entry point                                                                | S4 bucket origin          | Custom origin                              |
| ---------------------------------------------- | -------------------------------------------------------------------------- | ------------------------- | ------------------------------------------ |
| Origin (bucket or address), origin Host header | Domain details › **Domain details (域名详情)** › **Origin information (源站信息)** | You can change the bucket | You can change the address and Host header |
| Origin path prefix                             | Domain details › **Origin settings (回源设置)**                                | Supported                 | Not supported                              |
| Origin request headers                         | Domain details › **Origin settings**                                       | Supported                 | Supported                                  |

Every change requires a redeployment, which usually finishes within 30 seconds. A change takes effect when the status returns from **Deploying (部署中)** to **Running (运行中)**. You can't make changes while the domain is **Stopped (已停止)**.

## S4 bucket origin

The origin is a bucket in your account. The CDN carries the platform's authorization when it fetches from the origin, so the bucket can stay private and doesn't need public read.

> **Warning**
>
> CDN domains are public. Even if the bucket is private, the files in it can be accessed through the CDN domain. The bucket's [access control](https://docs.bitiful.com/en/bitiful-s4/handbook/anti-leech.md) and [public read rules](https://docs.bitiful.com/en/bitiful-s4/handbook/public-read.md) restrict anonymous requests that go directly to S4, not visitors who come through the CDN. To restrict visitors, use the CDN's [Hotlink protection and access control](https://docs.bitiful.com/en/cdn/handbook/access-control.md).

### Change the bucket

1. On the **Domain details** tab of the domain details page, click **Edit (编辑)** on the **Origin information** card.
2. In the **Change origin (修改回源)** dialog, choose the new bucket under **S4 bucket name (S4桶名称)** and click **Confirm (确认)**.

The new bucket must differ from the current one. Otherwise you see "回源桶未发生变化" (the origin bucket hasn't changed).

After the change, content from the old bucket that the edge has already cached isn't cleared automatically. Do a [directory purge](https://docs.bitiful.com/en/cdn/handbook/cache.md).

## Custom origin

The origin is your own HTTP or HTTPS service.

| Field                            | Rule                                                                                                                                                                                                              |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Origin address (源站地址)**        | Must start with `http://` or `https://`. The host is a domain or an IP, and can include a port, for example `https://source.mywebsite.com` or `http://203.0.113.10:8080`. It can't be the same as the CDN domain. |
| **Origin Host header (回源Host头)** | Optional. Enter a domain, without a protocol or port. It can't be an IP.                                                                                                                                          |

Notes:

- Only the protocol, host name, and port of the origin address are used. Any path after them is ignored. When a visitor requests `https://cdn.example.com/a/b.jpg`, the origin path is `/a/b.jpg`.
- If you don't specify a port, `https://` uses 443 and `http://` uses 80.
- When **Origin Host header** is empty, it's filled in automatically: if the origin address is a domain, that domain is used. If it's an IP, the CDN domain is used.
- If your origin serves different sites by Host, enter a domain your origin recognizes.

### Change the origin address

On the **Origin information** card, click **Edit**, enter the new **Origin address** and **Origin Host header**, and click **Confirm**.

> **Note**
>
> The dialog pre-fills the current values. An empty **Origin Host header** means it's filled in automatically, and the placeholder shows the value in use. Clearing a value you entered switches it back to automatic.

You can't change the origin type. To switch from custom origin to bucket origin (or the reverse), delete the domain and add it again. After you change the address, if the content differs, do a [directory purge](https://docs.bitiful.com/en/cdn/handbook/cache.md).

### Common messages

| Message                                                                                                         | What to do                                                                   |
| --------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| "回源地址必须包含<http://或者https://>" (the origin address must include http\:// or https\://)                           | Add the protocol.                                                            |
| "回源地址…的主机名不合法，请填写域名或 IP" (the host name in the origin address … is invalid, enter a domain or IP)               | Check the host name for spaces, Chinese characters, or other symbols.        |
| "加速域名不能与源站域名相同" (the CDN domain can't be the same as the origin domain)                                         | Prepare a separate domain for the origin, such as `origin.example.com`.      |
| "如需回源S4存储桶，请使用“桶回源”" (to fetch from an S4 bucket, use bucket origin)                                            | To fetch from Bitiful S4, create a new CDN domain with **S4 bucket origin**. |
| "host头不能包含端口" (the Host header can't include a port), "host头必须是一个合法域名" (the Host header must be a valid domain) | Enter only a domain in the origin Host header.                               |

## Origin path prefix

This maps the CDN domain's root path to a directory in the bucket. It's commonly used to host several sites in one bucket, or to switch between site versions. Only S4 bucket origin supports it.

| Origin path prefix    | Visitor requests                     | Object read          |
| --------------------- | ------------------------------------ | -------------------- |
| Not set (bucket root) | `https://cdn.example.com/index.html` | `index.html`         |
| `site/v2/`            | `https://cdn.example.com/index.html` | `site/v2/index.html` |

To set it:

1. Go to **Origin settings** and click **Edit** on the **Origin path prefix (回源路径前缀)** card.
2. Enter a directory, such as `site/v2/`. Leaving it empty means the bucket root. A mapping example appears below the input box.
3. Click **Confirm**. You see "修改成功，部署完成后生效" (changed successfully, takes effect after deployment).

Entry rules:

- A leading `/` is removed automatically, and a trailing `/` is added automatically
- Up to 512 bytes, and Chinese characters are supported
- No empty levels (consecutive `//`), and no level can be `.` or `..`
- It can't contain `*`, `!style`, or invisible characters

Effects:

- The edge cache is keyed by prefix. After you change the prefix, requests don't hit the cache of the old prefix, so you don't need to purge. Copies already cached in visitors' browsers aren't updated immediately.
- Once set, only objects under that directory are accessible through this domain. Image processing, styles, and other parameters work as usual.
- This changes the path only. For website behavior such as the home page and the 404 page, see [Static websites and domains](https://docs.bitiful.com/en/bitiful-s4/handbook/website.md).

## Origin request headers

These are extra request headers sent to your origin on origin fetch. Common uses: make your origin accept only requests from the CDN, or pass visitor information to your origin.

To set them:

1. Go to **Origin settings** and click **Edit** on the **Origin request headers (回源请求头)** card.
2. Click **Add request header (添加请求头)** and enter a name and a value. When you need a variable, put the cursor where you want it and choose one from the **Insert variable (插入变量)** drop-down.
3. Click **Save (保存)**. You see "保存成功，部署完成后生效" (saved successfully, takes effect after deployment).

Saving replaces everything: the list you submit this time is authoritative, and rows you deleted are removed.

### Entry rules

| Item                   | Rule                                                                                                                                 |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Count                  | Up to 10                                                                                                                             |
| Name                   | Up to 64 characters, letters, digits, and hyphens only, starting with a letter. Case-insensitive and can't be duplicated             |
| Value                  | Required, up to 512 characters. English letters, digits, spaces, and common symbols are allowed, and you can mix them with variables |
| Not allowed in a value | Chinese characters, double quotes, single quotes, backslashes, backticks, `#`. `$` and curly braces can be used only for variables   |

### Supported variables

A variable is written as `${variable_name}`. Only the following 11 are supported:

| Variable               | Description                                                                             | Example                          |
| ---------------------- | --------------------------------------------------------------------------------------- | -------------------------------- |
| `client_real_ip`       | The visitor's IP address                                                                | `203.0.113.8`                    |
| `request_scheme`       | The protocol the visitor used, http or https                                            | `https`                          |
| `client_country_code`  | The visitor's country or region (ISO 3166 code)                                         | `CN`                             |
| `client_province_code` | The code of the visitor's province in China                                             | For example `BJ`                 |
| `client_asn`           | The AS number of the visitor's network                                                  | `4134`                           |
| `client_http_version`  | The HTTP version the visitor used                                                       | `HTTP/1.1`                       |
| `client_ip_version`    | The visitor's IP version, 4 or 6                                                        | `4`                              |
| `client_isp`           | The visitor's carrier                                                                   | Depends on the visitor's network |
| `client_as_name`       | The AS name of the visitor's network                                                    | Depends on the visitor's network |
| `server_region`        | The country code of the CDN node the visitor connected to                               | `CN`                             |
| `server_province_code` | The code of the Chinese province where the CDN node the visitor connected to is located | For example `BJ`                 |

If a variable can't be resolved, it's empty. If the whole value is empty, the request header isn't sent.

### Request headers you can't set

The system uses these request headers:

| Scope                 | Request headers                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| All origin types      | `Host` (change it in **Origin information**), `Content-Length`, `Transfer-Encoding`, `Connection`, `Keep-Alive`, `TE`, `Trailer`, `Upgrade`, `Expect`, `Proxy-Authenticate`, `Proxy-Authorization`, `Proxy-Connection`, `HTTP2-Settings`, `Range`, `If-Range`, `If-Match`, `If-None-Match`, `If-Modified-Since`, `If-Unmodified-Since`, `Accept-Encoding`, `Content-Encoding`, `Via`, `CDN-Loop`, and any request header starting with `X-Btf-`, `Btf-`, `X-Bitiful-`, or `X-Req-Btf-` |
| S4 bucket origin only | `Authorization`, `Date`, `Content-MD5`, `Content-Type`, `Accept`, `Origin`, `Forwarded`, `X-Real-IP`, `X-Forwarded-For`, `X-Forwarded-Host`, `X-Forwarded-Proto`, `X-Forwarded-Port`, and any request header starting with `X-Amz-` or `X-CoreIX-`                                                                                                                                                                                                                                     |

### How they take effect

- If a visitor's request has a header with the same name, the value here overrides it, so visitors can't spoof it.
- They're sent only on origin fetch. A request that hits the edge cache doesn't go to the origin, so the origin doesn't receive it.
- The cache isn't keyed by these request headers. Don't make your origin return different content based on visitor information. Otherwise the content the first visitor gets is served to other visitors.

### Configuration examples

**Origin accepts only CDN requests**

For a custom origin, set a value that only you and your origin know:

| Name             | Value              |
| ---------------- | ------------------ |
| `X-Origin-Token` | `k7Wm2QxZ9tR4vB8n` |

Your origin checks this request header and rejects the request if it doesn't match, which prevents anyone from bypassing the CDN to reach your origin directly:

```text
if ($http_x_origin_token != "k7Wm2QxZ9tR4vB8n") { return 403; }
```

The above is an Nginx configuration and goes in the `server` block. When you rotate the secret, have your origin accept both the old and new values during the deployment.

**Pass the visitor IP and region**

| Name               | Value                                            |
| ------------------ | ------------------------------------------------ |
| `X-Client-IP`      | `${client_real_ip}`                              |
| `X-Client-Region`  | `${client_country_code}-${client_province_code}` |
| `X-Client-Network` | `isp=${client_isp}; asn=${client_asn}`           |

Suited to writing into origin logs. Requests that hit the cache don't reach your origin. To count all visitors, use [Access logs](https://docs.bitiful.com/en/console/access-logs.md).

## FAQ

<details>
<summary>The details page has no Origin settings</summary>

Some early CDN domains don't support origin path prefixes or origin request headers. You can delete the domain and add it again.

</details>

<details>
<summary>The origin returns 401, but visitors see 403</summary>

The edge shows the origin's 400, 401, 402, 403, and 405 all as a 403 page, and 500 to 506 all as a 502 page. When troubleshooting, check your origin's own logs.

</details>

<details>
<summary>I changed a file at the origin, but visitors still see the old content</summary>

Both the edge and browsers cache content. See [Cache, purge, and prefetch](https://docs.bitiful.com/en/cdn/handbook/cache.md).

</details>

<details>
<summary>Saving shows “发生错误，请稍后重试” (an error occurred, try again later)</summary>

The domain may be starting or stopping, or may already be stopped. Wait until the status is **Running** and try again.

</details>
