# Hotlink protection and access control

> Use Referer, IP, and User-Agent allowlists and denylists, plus advanced authentication, to restrict who can access a CDN domain.

A CDN domain is open to everyone by default. Access control blocks hotlinking, abnormal clients, and unauthorized access, and cuts unnecessary data transfer charges.

Entry point: **CDN › Static acceleration management (静态加速管理) ›** the domain's **Manage (管理) › Access control (访问控制)**.

| Method                                                                                          | Suited for                                                          | Strength                      |
| ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ----------------------------- |
| Referer list                                                                                    | Stopping other sites from embedding your images and videos directly | Low. Referer can be forged    |
| User-Agent list                                                                                 | Blocking known crawlers and download tools                          | Low. User-Agent can be forged |
| IP list                                                                                         | Allowing only your office network, or blocking abnormal IPs         | High                          |
| [Advanced authentication](https://docs.bitiful.com/bitiful-s4/intro.md#advanced-authentication) | Paid content, private files, and time-limited links                 | High                          |

You can use several methods together. A visitor must **pass all of them** to get access, and failing any one returns `403`. Requests that fail are rejected directly at the edge and don't go to the origin.

> **Note**
>
> You can't make changes while the domain is **Stopped (已停止)**. After you save, the status becomes **Deploying (部署中)**, which usually takes 30 seconds, and the change takes effect once the status returns to **Running (运行中)**.

## Hotlink protection

On the **Hotlink protection (防盗链)** card, click **Edit (编辑)**, fill in the fields, and click **Save (保存)**. Referer, IP, and User-Agent are on the same card, and one save replaces all of them.

**Allowlist active (白名单生效)** means only entries in the list can access. **Denylist active (黑名单生效)** means only entries in the list are denied. The default is denylist active with an empty list, which means no restriction.

### Referer

| Field                                                                     | Values                                                              | Description                                                                                                                           |
| ------------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| **Empty Referer (空 Referer)**                                             | **On (allow access) (开启（允许访问）)**, **Off (deny access) (关闭（不允许访问）)** | Whether to allow requests that have no Referer. Direct browser visits, apps, mini programs, and download tools often send no Referer. |
| **Referer hotlink protection type (Referer 防盗链类型)**                       | **Allowlist active**, **Denylist active**                           | When the allowlist is active, the list can't be empty.                                                                                |
| **Referer allowlist (Referer 白名单)** or **Referer denylist (Referer 黑名单)** | One domain per line                                                 | Up to 2,000 characters in total.                                                                                                      |

List format:

- Enter only the domain, without a protocol or port, for example `www.example.com`
- Use `*.` to match subdomains, for example `*.example.com`. `*` can appear only at the start
- To allow both the root domain and its subdomains, write two lines: `example.com` and `*.example.com`

Example: allow only your own website to embed images, and also allow direct visits.

| Field                               | Value                                         |
| ----------------------------------- | --------------------------------------------- |
| **Empty Referer**                   | On (allow access)                             |
| **Referer hotlink protection type** | Allowlist active                              |
| **Referer allowlist**               | `example.com`, `*.example.com` (one per line) |

### IP

| Field                                                 | Values                                    | Description                                                                                                        |
| ----------------------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| **IP hotlink protection type (IP 防盗链类型)**             | **Allowlist active**, **Denylist active** | When the allowlist is active, the list can't be empty.                                                             |
| **IP allowlist (IP 白名单)** or **IP denylist (IP 黑名单)** | One IPv4 address or CIDR block per line   | CIDR format such as `203.0.113.0/24`, with a mask of 1 to 32. Up to 2,000 characters in total, and no blank lines. |

### User-Agent

| Field                                                                                 | Values                                    | Description                                                          |
| ------------------------------------------------------------------------------------- | ----------------------------------------- | -------------------------------------------------------------------- |
| **User-Agent hotlink protection type (User-Agent 防盗链类型)**                             | **Allowlist active**, **Denylist active** | When the allowlist is active, the list can't be empty.               |
| **User-Agent allowlist (User-Agent 白名单)** or **User-Agent denylist (User-Agent 黑名单)** | One signature per line                    | Up to 2,000 characters in total, no blank lines, and no backslashes. |

Matching rules: a visitor's User-Agent matches if it contains the signature, case-insensitively. `*` matches any number of characters, and other symbols match literally.

| Signature         | Matches                | Doesn't match        |
| ----------------- | ---------------------- | -------------------- |
| `curl`            | `curl/8.4.0`           | `Mozilla/5.0 …`      |
| `python*requests` | `python-requests/2.31` | `Python-urllib/3.11` |

Don't make signatures too short. For example, putting `Mozilla` in the denylist blocks almost every browser.

### Messages when saving

| Message                                                                                                            | What to do                                                                                                                   |
| ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| "白名单生效 且 白名单为空 将导致所有匿名请求均会被拒绝" (an active allowlist that's empty will cause all anonymous requests to be denied)   | One of the allowlists is empty. Saving still fails after you confirm, so fill in the allowlist or switch to denylist active. |
| "配置白名单生效时，白名单不能为空" (when the allowlist is active, it can't be empty)                                               | Fill in the Referer, IP, or User-Agent allowlist, or switch to denylist active.                                              |
| "… 不应包含协议" (… shouldn't include a protocol)                                                                        | Remove prefixes such as `https://` from the Referer.                                                                         |
| "… \*只能出现在首部" (… `*` can appear only at the start), "… 使用模糊匹配时必须以\*.开头" (… wildcard matching must start with `*.`) | Change it to the `*.example.com` format.                                                                                     |
| "IP 名单第N行 … 不是合法的 IP 或 CIDR，每行只能填写一个" (line N of the IP list … isn't a valid IP or CIDR, one per line)             | Check the format and remove blank lines and extra commas.                                                                    |
| "UA 名单第N行 … 为空，请删除空行" (line N of the UA list … is empty, delete blank lines)                                       | Delete the blank lines.                                                                                                      |

## Advanced authentication

When this is on, only links with a correct signature that haven't expired can be accessed. Your server computes the signature with a secret key, and the link carries an expiration time. It suits paid content and private files.

To turn it on:

1. On the **Advanced authentication (高级鉴权)** card, click **Edit** and select **On** for **Status (状态)**.
2. Enter the **Key value (密钥值)**: letters and digits only, 8 to 30 characters.
3. Click **Save** and wait until the status returns to **Running**.

Link format (with no other parameters):

```text
https://<CDN domain><path>?_btf_tk=<signature>&_ts=<expiration time>
```

| Parameter | Description                                                                                                                                          |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `_ts`     | The link's expiration time, as a Unix timestamp in seconds. After this time the link returns 403. A request without this parameter also returns 403. |
| `_btf_tk` | The signature: the lowercase hex of `MD5(key + path + _ts)`.                                                                                         |

Verify the key and rules from the command line:

```bash
KEY="your key value"
DOMAIN="cdn.example.com"
URI_PATH="/image.jpg"
TS=$(( $(date +%s) + 600 ))
TOKEN=$(printf '%s%s%s' "$KEY" "$URI_PATH" "$TS" | openssl md5 | awk '{print $NF}')

curl -I "https://${DOMAIN}${URI_PATH}?_btf_tk=${TOKEN}&_ts=${TS}"
```

When the URL also carries image processing or other parameters, those parameters must be signed too. For the rules and code in each language, see [Advanced hotlink protection for CDN](https://docs.bitiful.com/en/best-practice/token-link.md).

Notes:

- Once on, every link on the whole CDN domain needs a signature. There's no per-directory option. Use separate CDN domains for public and private resources.
- `_btf_tk` and `_ts` aren't part of the cache key, so different signed links to the same file share one cache entry.
- After you change the key, all old links stop working. Have your server prepare the new key first, and switch after deployment completes.
- Don't put the key in client code such as web pages or apps.

## IP rate limiting

This limits the number of requests per second from a single IP on a single node, and returns `429` when exceeded.

This setting appears only on domains where it's **already on**. New domains can't turn it on. For **Per-IP access threshold (单 IP 访问阈值)**, enter an integer greater than 0, in QPS. Once it's turned off, the card no longer appears, and you can't turn it back on yourself.

## Relationship to other settings

- A 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. If you need to restrict both, set each separately.
- The console currently has no settings for blocking by country or region, or for capping bandwidth.

## FAQ

<details>
<summary>After I set a Referer allowlist, opening an image directly also returns 403</summary>

When you open a file directly in the browser address bar, there's no Referer. Set **Empty Referer** to **On (allow access)**.

</details>

<details>
<summary>Images fail to load in an app or mini program</summary>

Apps usually send no Referer, or send the platform's own domain. Allow an empty Referer, or switch to [advanced authentication](https://docs.bitiful.com/en/best-practice/token-link.md).

</details>

<details>
<summary>The rules didn't take effect after saving</summary>

Confirm the status has returned to **Running**. The browser may still have a local cache, so test in an incognito window or with `curl`.

</details>

<details>
<summary>How can I see who is accessing?</summary>

Check recent IPs, Referers, User-Agents, and status codes in [Access logs](https://docs.bitiful.com/en/console/access-logs.md), then decide which list to add them to.

</details>
