> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.bitiful.com/en/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.bitiful.com/_mcp/server.

# Edge rules

> Apply authentication, blocking, redirects, caching, speed limits, CORS, and headers by path, region, IP, request header, and more, and customize error pages.

Settings such as [access control](https://docs.bitiful.com/en/cdn/handbook/access-control.md) and [caching](https://docs.bitiful.com/en/cdn/handbook/cache.md) apply to the whole CDN domain. Edge rules let some requests use different settings. For example, only `/private/` needs a signature, or only web pages aren't cached.

Entry point: **CDN › Static acceleration management (静态加速管理) ›** the domain's **Manage (管理) › Rules (规则)**.

> **Note**
>
> Some early CDN domains don't support edge rules, and their details page has no **Rules** tab. You can delete the domain and add it again.

## How rules work

A rule has conditions and actions: when a request meets the conditions, the actions run.

- **Conditions**: **all** conditions must be met. When one condition has several values, meeting **any one** of them is enough. A rule without conditions matches every request.
- **Actions**: one rule can have several actions.
- **Order**: rules run from top to bottom. Use the arrow buttons to reorder them.

| Action                                                                                                                        | When several rules match                                                                       |
| ----------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| Block, redirect                                                                                                               | The **first** matching rule runs                                                               |
| Advanced authentication, CORS, download or preview, per-connection speed limit, CDN cache time, browser cache time, cache key | The **last** matching rule wins                                                                |
| Response headers, origin request headers, cache time by status code                                                           | The last rule wins for the same header or status code, and the rest are merged                 |
| Skip hotlink protection lists, no cache                                                                                       | One match is enough. If a later rule sets the CDN cache time, it cancels an earlier "no cache" |

Order of evaluation: blocking, advanced authentication, and the hotlink protection lists (Referer and User-Agent) come first, then redirects. IP lists are checked after redirects.

## Add a rule

### Create a rule

Click **New rule (新建规则)** and enter a **Name (名称)**. You can also click **Add from template (从模板添加)** and adjust it.

### Set conditions

Click **Add condition (添加条件)**, choose the condition type and comparison, type a value, and press Enter. Pasting several lines adds several values.

### Set actions

Click **Add action (添加动作)**, choose an action, and fill it in.

### Test

Click **OK (确定)** to return to the list, and check the result with [Test rules](https://docs.bitiful.com/bitiful-s4/intro.md#test-rules) at the bottom of the page. Nothing is saved yet.

### Save and deploy

Click **Save and deploy (保存并部署)**. You see "保存成功，部署完成后生效" (saved successfully, takes effect after deployment). The rules take effect once the status goes from **Deploying (部署中)** back to **Running (运行中)**, usually within 30 seconds.

While the page shows "有未保存的修改" (unsaved changes), all changes exist only on the current page. Click **Discard changes (放弃修改)** to undo them. You can't make changes while the domain is **Stopped (已停止)**.

### Observe mode

For a new rule, you can turn on **Observe mode (观察模式)** first: actions don't run, and matches are only shown. Turn on [match records](https://docs.bitiful.com/bitiful-s4/intro.md#see-which-rules-matched-in-production), confirm the scope, then turn observe mode off.

### Disable all rules

If rules cause access problems, click **Disable all (停用全部)**. All rules are disabled and deployed immediately. Advanced authentication goes back to requiring a signature on every request. Error pages aren't affected.

## Conditions

Every condition can be negated, for example **doesn't satisfy "starts with" (不满足“开头是”)**, **is not (不是)**, and **doesn't exist (不存在)**.

| Condition                               | Comparison                                               | Value                                                                                                                                           |
| --------------------------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| **Path (路径)**                           | starts with, equals, ends with, contains, wildcard match | Such as `/public/`. Case-sensitive, without the domain or parameters. Enter Chinese characters as is                                            |
| **File extension (文件扩展名)**              | is                                                       | Such as `jpg`, without the dot, case-insensitive                                                                                                |
| **Visitor country or region (访客国家或地区)** | is                                                       | Two uppercase letters, such as `CN` or `US`                                                                                                     |
| **Visitor province, China (访客省份（中国）)**  | is                                                       | Province code, such as `BJ`                                                                                                                     |
| **Visitor IP (访客 IP)**                  | is                                                       | IPv4 or IPv6 address or range, such as `203.0.113.0/24`                                                                                         |
| **Visitor carrier (访客运营商)**             | is                                                       | Carrier name, with the same values as the `client_isp` variable in [origin request headers](https://docs.bitiful.com/en/cdn/handbook/origin.md) |
| **Visitor AS number (访客 AS 编号)**        | is                                                       | Such as `4134`                                                                                                                                  |
| **IP version (IP 版本)**                  | is                                                       | `4` or `6`                                                                                                                                      |
| **Request method (请求方法)**               | is                                                       | `GET`, `HEAD`, `POST`, and others                                                                                                               |
| **Protocol (协议)**                       | is                                                       | `http` or `https`                                                                                                                               |
| **Query parameter (查询参数)**              | exists, equals, starts with, contains                    | Enter the parameter name first                                                                                                                  |
| **Request header (请求头)**                | exists, equals, starts with, contains                    | Enter the header name first                                                                                                                     |
| **Cookie**                              | exists, equals, starts with, contains                    | Enter the cookie name first                                                                                                                     |
| **User-Agent**                          | contains, exists                                         | Case-insensitive, `*` is allowed                                                                                                                |
| **Referer**                             | domain is, exists                                        | `example.com` or `*.example.com`                                                                                                                |

Notes:

- **Path** is compared after decoding. Prefixes and full paths must start with `/`. Write the trailing `/` for a directory, because `/public` also matches `/publicity/a.jpg`.
- In a **wildcard match**, `*` matches any number of characters, including `/`. Use 1 to 3 of them, not next to each other. For example, `/user/*/private/*`.
- With S4 bucket origin, the path doesn't include the style suffix. `/a.jpg!style:thumb` is evaluated as `/a.jpg`.
- When an [origin path prefix](https://docs.bitiful.com/en/cdn/handbook/origin.md) is set, rules use the path the visitor requests, without the prefix.
- When a visitor requests a directory and the origin returns its home page, the home page's file name and extension aren't used for matching. To match home pages, use **Path equals `/`** or **Path ends with `/`**.
- Values of query parameters, request headers, and cookies are case-sensitive, and only English letters, digits, and common symbols are supported.
- The host bits of a range must be 0. The mask of an IPv6 range must be a multiple of 16, and no group in the prefix can be 0.

## Actions

### Access control

<details open>
<summary>Advanced authentication (高级鉴权)</summary>

Decides whether matching requests need a signature. You must first turn on [advanced authentication](https://docs.bitiful.com/en/cdn/handbook/access-control.md) under **Access control**.

| Option                          | Meaning                                            |
| ------------------------------- | -------------------------------------------------- |
| **No signature needed (免签名访问)** | The signature isn't checked, and anyone can access |
| **Signature required (必须签名)**   | The signature and expiration time are checked      |

Once advanced authentication is on, requests that match no rule need a signature. So a **Signature required** rule on its own has no effect. Let other paths skip the signature first, as shown in the [examples](https://docs.bitiful.com/bitiful-s4/intro.md#examples).

With custom origin, **No signature needed** is case-sensitive, while **Signature required** and **Block** ignore case, because some origins do. If your origin rewrites paths, skip the signature only for directories you know are public. Don't use "no signature by default, signature required for some directories".

With S4 bucket origin, images referenced by the `mark` image watermark parameter are evaluated with the same rules: a path that needs no signature can't reference an image that does.

</details>

<details open>
<summary>Block (拦截)</summary>

Returns 403, 404, 410, or 451 directly, without an origin fetch. With custom origin, path conditions ignore case.

</details>

<details open>
<summary>Skip hotlink protection lists (跳过防盗链名单)</summary>

Matching requests aren't checked against the **Referer list (Referer 名单)** or the **User-Agent list (User-Agent 名单)**. You can select both. IP lists can't be skipped.

</details>

<details open>
<summary>CORS (跨域)</summary>

| Option                                 | Meaning                                                                     |
| -------------------------------------- | --------------------------------------------------------------------------- |
| **Allow all origins (允许所有来源)**         | `Access-Control-Allow-Origin: *`                                            |
| **Allow only these origins (只允许以下来源)** | Write origins as `https://example.com` or `https://*.example.com`, up to 20 |
| **No CORS headers (不返回跨域头)**           | Removes the allowed origin from the global setting and from your origin     |

Other CORS response headers are the same as in [CORS configuration](https://docs.bitiful.com/en/cdn/handbook/performance.md).

</details>

### Request and response

<details open>
<summary>Redirect (重定向)</summary>

The status code can be 301, 302, 307, or 308.

| Type                              | Example                                                                                  |
| --------------------------------- | ---------------------------------------------------------------------------------------- |
| **Fixed address (固定地址)**          | Everything redirects to `https://example.com/new.html`, or to `/new.html` on this domain |
| **Replace path prefix (替换路径前缀)**  | Replace `/old/` with `/new/`: `/old/a/b.html` redirects to `/new/a/b.html`               |
| **Redirect to HTTPS (跳转到 HTTPS)** | Applies to HTTP requests only. Path and parameters don't change                          |

With **Keep query parameters (保留查询参数)** on, the original parameters are carried to the new address. The prefix being replaced can be up to 100 characters and supports only English letters, digits, and common symbols, and Chinese characters in the target must be URL-encoded. If the target still meets this rule's path conditions, saving reports a redirect loop.

</details>

<details open>
<summary>Response headers (响应头)</summary>

Sets or removes response headers returned to visitors, up to 10. They override headers of the same name from your origin. Values can use the [origin request header variables](https://docs.bitiful.com/en/cdn/handbook/origin.md).

For `Cache-Control`, use **Browser cache time**. For `Content-Disposition`, use **Download or preview**. For `Access-Control-*`, use **CORS**. Headers such as `Content-Length`, `ETag`, `Set-Cookie`, `Location`, and `Server` are managed by the system and can't be set.

</details>

<details open>
<summary>Origin request headers (回源请求头)</summary>

Sets or removes request headers on origin fetch, up to 10. The rules for names, values, and variables are the same as in [origin request headers](https://docs.bitiful.com/en/cdn/handbook/origin.md), and settings of the same name there are overridden.

When the conditions depend on more than the path, matching and non-matching requests are cached separately. When a value uses variables, the cache isn't keyed by them, so your origin shouldn't return different content based on them.

</details>

<details open>
<summary>Download or preview (下载或预览)</summary>

| Option                              | Response header                   |
| ----------------------------------- | --------------------------------- |
| **Download as attachment (作为附件下载)** | `Content-Disposition: attachment` |
| **Preview in browser (浏览器内预览)**     | `Content-Disposition: inline`     |

If the link already sets a file name with [response-content-disposition](https://docs.bitiful.com/en/cdn/handbook/performance.md), **Download as attachment** keeps that file name.

</details>

<details open>
<summary>Per-connection speed limit (单连接限速)</summary>

Limits the download speed of each request, from 64 to 32768 KB/s, replacing the global [per-connection speed limit](https://docs.bitiful.com/en/cdn/handbook/performance.md). The first 1 MiB of a matching request isn't limited. Requests that don't match aren't affected.

</details>

### Caching

<details open>
<summary>CDN cache time (CDN 缓存时间)</summary>

How long the edge caches successful responses, from 1 second to 365 days. A change affects only content cached afterward. [Purge](https://docs.bitiful.com/en/cdn/handbook/cache.md) what's already cached. After the cache expires, the edge updates it in the background, and requests may still get the old content until the update finishes. If that isn't acceptable, use **No cache**.

</details>

<details open>
<summary>Cache time by status code (按状态码的缓存时间)</summary>

Sets cache times for errors and redirects, from 1 second to 1 day.

| Origin type      | Status codes                            |
| ---------------- | --------------------------------------- |
| S4 bucket origin | 301, 302, 307, 308, 404, 410, 451       |
| Custom origin    | The above, plus 403, 500, 502, 503, 504 |

By default, 404 is cached for 5 seconds and others aren't cached.

</details>

<details open>
<summary>Browser cache time (浏览器缓存时间)</summary>

| Option                            | `Cache-Control` returned                    |
| --------------------------------- | ------------------------------------------- |
| **Cache for a while (缓存一段时间)**    | `public, max-age=<seconds>`, up to 365 days |
| **Revalidate every time (每次都校验)** | `no-cache`                                  |
| **Don't cache (不缓存)**             | `no-store`                                  |

</details>

<details open>
<summary>No cache (不缓存)</summary>

The edge doesn't store the content, and every request goes to the origin, so data transfer and request charges go up. If no browser cache time is set, browsers also revalidate every time.

</details>

<details open>
<summary>Cache key (缓存键)</summary>

Decides which differences are cached separately.

| Item                     | S4 bucket origin                                                         | Custom origin                                                                                                               |
| ------------------------ | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- |
| Query parameters         | Default (image processing parameters), also distinguish these parameters | Default (all parameters), all parameters, ignore all parameters, distinguish only these parameters, ignore these parameters |
| Request headers, cookies | By the names you list, up to 10 each                                     | Same                                                                                                                        |
| Device type              | Phone, tablet, desktop                                                   | Same                                                                                                                        |
| Country or region        | The visitor's country or region                                          | Same                                                                                                                        |

The finer the key, the lower the hit ratio and the more origin fetches. Your origin still receives all parameters.

</details>

### Actions that can't be in the same rule

Block and redirect. No cache with CDN cache time, cache time by status code, or cache key.

## Examples

**Make one directory public**

Everything needs a signature except `/public/`. Turn on advanced authentication first, then add:

| Order | Condition                   | Action                                       |
| :---: | --------------------------- | -------------------------------------------- |
|   1   | Path starts with `/public/` | Advanced authentication: no signature needed |

Template: **指定目录免签名，其余必须签名** (selected directories need no signature, the rest do).

**Protect one directory**

Turn on advanced authentication first, then add:

| Order | Condition                    | Action                                       |
| :---: | ---------------------------- | -------------------------------------------- |
|   1   | All requests                 | Advanced authentication: no signature needed |
|   2   | Path starts with `/private/` | Advanced authentication: signature required  |

Don't swap the order. Template: **指定目录必须签名，其余公开** (selected directories need a signature, the rest are public).

**Allow only some regions**

| Condition                                   | Action     |
| ------------------------------------------- | ---------- |
| Visitor country or region is not `CN`, `HK` | Block: 403 |

Template: **只允许指定国家或地区访问** (allow only selected countries or regions). To limit it to one directory, add a path condition.

**Cache by directory**

| Order | Condition                                | Action                                                     |
| :---: | ---------------------------------------- | ---------------------------------------------------------- |
|   1   | Path starts with `/api/`                 | No cache                                                   |
|   2   | Path starts with `/img/`, `/api/static/` | CDN cache time: 1 hour; browser cache time: 60 seconds     |
|   3   | Path starts with `/img/live/`            | CDN cache time: 5 seconds; browser cache time: don't cache |

Put parent directories first and subdirectories after them, because later rules override earlier ones. Paths that match no rule use the [default cache policy](https://docs.bitiful.com/en/cdn/handbook/cache.md).

**Keep web pages fresh**

| Condition                       | Action                                              |
| ------------------------------- | --------------------------------------------------- |
| File extension is `html`, `htm` | No cache; browser cache time: revalidate every time |
| Path ends with `/`              | No cache; browser cache time: revalidate every time |

The first rule is the template **网页不缓存** (don't cache web pages). The second covers home pages of the site and its directories. With heavy traffic, use a **CDN cache time** of 60 seconds instead to reduce origin fetches.

**Skip the Referer check for an app**

You have a global Referer allowlist, and your app sends no Referer:

| Condition                    | Action                                      |
| ---------------------------- | ------------------------------------------- |
| User-Agent contains `MyApp/` | Skip hotlink protection lists: Referer list |

User-Agent can be forged. For strict control, use advanced authentication.

## Custom error pages

On the **Custom error pages (自定义错误页)** card of the **Rules** tab, choose what to show for each kind of error. They're saved together with rules, apply to the whole domain, and work even without any rules.

| Error                                | Status codes covered                         |
| ------------------------------------ | -------------------------------------------- |
| **403 Access denied (403 拒绝访问)**     | 400, 401, 402, 403, 405, all returned as 403 |
| **404 Not found (404 不存在)**          | 404                                          |
| **429 Too many requests (429 请求过多)** | 429                                          |
| **5xx Origin error (5xx 源站错误)**      | 500 to 506, all returned as 502              |

| Option                      | Description                                                                         |
| --------------------------- | ----------------------------------------------------------------------------------- |
| **Default page (默认页面)**     | The built-in error page                                                             |
| **Custom page (自定义页面)**     | HTML, up to 4096 bytes. The status code doesn't change                              |
| **Redirect to URL (跳转到网址)** | A 302 redirect to an address that starts with `http(s)://`. It can't be this domain |

Use full URLs for images and styles on the page, and make sure they don't trigger the same error.

## Test rules

On the **Test rules (测试规则)** card, enter a URL or path, optionally with the method, visitor IP, country code, province code, and request headers, then click **Test (测试)**. You see which rules match and the result of each setting.

- The result is calculated from the rules on the current page, including unsaved changes. No request is actually sent.
- It doesn't check whether a signature is valid, or the global hotlink protection lists.
- "路径写法不规范" (irregular path) means the path contains `.` or `..` levels, control characters, or repeated encoding. With custom origin, it also covers `;` and backslashes. For safety, actions that loosen access, such as no signature needed and skipping lists, don't apply, and block rules are treated as matched. Normal links don't cause this.

### See which rules matched in production

Turn on **Return matched rules in the X-Btf-Rules response header (在响应头 X-Btf-Rules 里返回命中的规则)**, save, and check with `curl`:

**macOS**

```bash
curl -sI "https://cdn.example.com/public/a.jpg" | grep -i x-btf-rules
```

**Linux**

```bash
curl -sI "https://cdn.example.com/public/a.jpg" | grep -i x-btf-rules
```

**Windows**

```powershell title="PowerShell"
curl.exe -sI "https://cdn.example.com/public/a.jpg" | Select-String x-btf-rules
```

The header contains the IDs of matched rules, including rules in observe mode. Entries that start with `!` are internal marks. While this is on, the rule list shows each rule's ID. Turn it off when you're done.

## Limits

| Item                                     | Limit                                                    |
| ---------------------------------------- | -------------------------------------------------------- |
| Rules                                    | 20 per domain                                            |
| Conditions                               | 5 per rule, 20 values per condition, 256 bytes per value |
| Response headers, origin request headers | 10 of each per rule                                      |
| Rule name                                | 50 characters                                            |
| Redirect target                          | 1024 characters                                          |
| Custom error page                        | 4096 bytes each                                          |

All rules together are limited to about 24 KB. Beyond that, you see "内容过多，请减少规则或条件的值" (too much content, reduce rules or condition values).

## FAQ

<details>
<summary>Saving shows "规则已被修改，请刷新后重新编辑"</summary>

Someone else, or another window, saved the rules first. Refresh the page, make your changes again, and save.

</details>

<details>
<summary>I can't turn off advanced authentication</summary>

You can't turn it off while any enabled rule uses the **Advanced authentication** action. Disable or delete those rules and save first.

</details>

<details>
<summary>A rule doesn't take effect</summary>

1. Confirm you clicked **Save and deploy** and the status is back to **Running**.
2. Check the conditions with **Test rules**. Watch for letter case and the trailing `/` of directories.
3. Caching actions affect only content cached afterward. [Purge the cache](https://docs.bitiful.com/en/cdn/handbook/cache.md) first.
4. The browser may have cached an old response or a 301 redirect. Test with an incognito window or `curl`.

</details>

<details>
<summary>Can rules restrict direct access to the bucket?</summary>

No. Rules affect only this CDN domain. For direct access to the bucket, use [public read](https://docs.bitiful.com/en/bitiful-s4/handbook/public-read.md) and [access control](https://docs.bitiful.com/en/bitiful-s4/handbook/anti-leech.md).

</details>

<details>
<summary>Can content cached before a block rule still be accessed?</summary>

No. Blocking and authentication are evaluated before the cache is read, so they apply as soon as the rule takes effect. Copies already in visitors' browsers aren't affected.

</details>
