docs(config): add a routing guide for Happ, Clash/Mihomo and Incy (#7183)

Explain, in English and Russian, how the subscription settings feed routing profiles to Happ, Clash/Mihomo and Incy: inline values and remote HTTPS sources, how the panel caches and validates a remote file, the size limits, and what each client receives.

The guide states the limits and checks the code applies: the 8 KiB Happ value after Base64 encoding, remote Clash files validated on their own, Incy URLs handed to the app without being fetched, and the log line each source writes.
This commit is contained in:
Mikail Katsiev
2026-11-24 15:40:48 +03:00
committed by GitHub
parent e7bef4813d
commit ccdda6f728
4 changed files with 821 additions and 0 deletions
+1
View File
@@ -12,6 +12,7 @@
"transports",
"clients",
"subscription",
"routing-profiles",
"share-links"
]
}
@@ -0,0 +1,408 @@
---
title: Routing for Happ, Clash/Mihomo and Incy
description: How to write the JSON and YAML routing profiles served in subscriptions — the Happ format, Clash/Mihomo rules and the Incy profile — and how the panel accepts and validates them.
icon: GitBranch
---
The panel can hand clients a ready routing profile: which sites and IPs go
direct, which go through the proxy and which are blocked. The profile format
depends on the app:
| App | Profile format | Where to set it in the panel |
| ------------------ | ----------------------------------- | ------------------------------------------- |
| **Happ** | JSON (as a `happ://` link) | Subscription settings → **Happ** tab |
| **Clash / Mihomo** | YAML (rules, groups, providers) | **Clash / Mihomo** tab |
| **Incy** | JSON (as an `incy://` link) | **Incy** tab → **Routing** |
Each of the three fields accepts **either the profile itself** (inline) **or
one permanent HTTPS URL** to a file, for example a raw gist. A URL lets you
change the rules without opening the panel.
## How the panel handles a remote URL
In the Happ and Clash / Mihomo fields, a value that is a single `https://...`
line is treated as a remote source that the panel fetches itself:
- the panel downloads it **in the background** and caches it for 10 minutes; a
subscription request never waits for the source;
- the file is validated; if it is invalid the panel **keeps serving the last
working value** and logs a warning;
- only `https://` is allowed, with no credentials in the URL, and the host must
be public (local and internal addresses are blocked);
- redirects are followed (up to 5) but must stay on `https://`;
- limits: Clash 2 MiB; Happ 16 KiB for the download and 8 KiB for the value
after Base64 encoding, which is about 6 KiB of JSON; 6 second request timeout.
The Incy field is different: the panel never downloads an Incy URL. It only
checks that the URL is `https://` without credentials and hands it to the app,
which fetches and refreshes the profile itself (see the Incy section below).
Use the **raw** link (`gist.githubusercontent.com/.../raw/...`), not the gist
page.
---
## Happ
### Where to enter it
**Settings → Subscription → Happ → Routing & rules**:
1. turn on **Enable routing** (sends `Routing-Enable: true`);
2. put one of these in **Routing rules**:
- a ready `happ://routing/onadd/<base64>` link;
- a permanent HTTPS URL to **JSON** or to a file containing a `happ://` link;
- `happ://routing/off` to turn routing off on the client.
The panel sends the value to the client in the `Routing` header. If the HTTPS
file contains plain JSON, the panel converts it to
`happ://routing/onadd/<base64>` itself. The source may also answer with a
redirect to `happ://...`, which is accepted too (this is how services such as
routing.help publish a profile).
If the field is empty but the **JSON subscription routing profile**
(`subJsonRoutingRules`) is set, that profile is sent as the `Routing` header
automatically.
The fastest start is the **routing presets** (Iran Bypass, China Direct,
Global, LAN bypass, optionally with ad blocking) or the **visual rule
builder**, which loads the current profile and lets you edit the lists or the
full JSON.
### JSON format
A profile is one JSON object. Happ writes flag values as strings (`"true"`,
`"false"`) and lists as arrays of strings.
```json
{
"Name": "My Routing",
"GlobalProxy": "true",
"RouteOrder": "block-proxy-direct",
"RemoteDNSType": "DoH",
"RemoteDNSDomain": "https://cloudflare-dns.com/dns-query",
"RemoteDNSIP": "1.1.1.1",
"DomesticDNSType": "DoH",
"DomesticDNSDomain": "https://dns.alidns.com/dns-query",
"DomesticDNSIP": "223.5.5.5",
"DnsHosts": {
"cloudflare-dns.com": "1.1.1.1",
"dns.alidns.com": "223.5.5.5"
},
"DirectSites": ["geosite:private", "geosite:cn", "domain:example.cn"],
"DirectIp": ["geoip:cn", "geoip:private", "192.168.0.0/16"],
"ProxySites": [],
"ProxyIp": [],
"BlockSites": ["geosite:category-ads-all"],
"BlockIp": [],
"DomainStrategy": "IPIfNonMatch",
"FakeDNS": "false",
"UseChunkFiles": "true"
}
```
| Field | Type | Meaning |
| ----- | ---- | ------- |
| `Name` | string | Profile name shown in the app. |
| `GlobalProxy` | `"true"`/`"false"` | Global mode: anything not matched by a rule goes through the proxy. |
| `RouteOrder` | string | Group check order joined by dashes: `block-proxy-direct`, `block-direct-proxy`, … The **first** matching group wins. Allowed words: `block`, `proxy`, `direct`; repeats are ignored. |
| `DirectSites` / `ProxySites` / `BlockSites` | array of strings | Domains: direct / via proxy / blocked. |
| `DirectIp` / `ProxyIp` / `BlockIp` | array of strings | IPs and subnets, same three groups. |
| `RemoteDNSDomain`, `RemoteDNSIP`, `RemoteDNSType` | string | DNS for proxied traffic (`DoH` and an `https://.../dns-query` address). |
| `DomesticDNSDomain`, `DomesticDNSIP`, `DomesticDNSType` | string | DNS for the "direct" domains. |
| `DnsHosts` | object name → IP | Static records, so DoH hosts do not need DNS to resolve themselves. |
| `DomainStrategy` | string | Xray strategy: `AsIs`, `IPIfNonMatch`, `IPOnDemand`. |
| `FakeDNS`, `UseChunkFiles` | `"true"`/`"false"` | Happ extensions; the panel passes them to the client unchanged. |
Unknown fields are **not lost**: the panel and the editor keep them and pass
them to Happ.
### List entry syntax
Entries use Xray routing syntax:
| Entry | Matches |
| ----- | ------- |
| `geosite:category-ads-all` | A category from `geosite.dat`. |
| `geosite:private`, `geoip:private` | Local/private addresses. |
| `geoip:ir`, `geoip:cn` | A country from `geoip.dat`. |
| `domain:example.com` | The domain and all its subdomains. |
| `full:www.example.com` | Exactly this domain. |
| `keyword:ads` | Any domain containing the substring. |
| `regexp:\\.ru$` | A regular expression. |
| `10.0.0.0/8`, `1.2.3.4` | A CIDR subnet or a single IP. |
An entry without a prefix is a domain substring; write `domain:` for precision.
`geosite:`/`geoip:` categories must exist in the client's `.dat` files; the
panel sends them in the `Routing` header so Happ fetches the right geo files.
### Building a `happ://` link by hand
A link is the prefix plus the JSON in Base64 (UTF-8):
```text
happ://routing/onadd/<base64 of the JSON>
```
`onadd` adds the profile and activates it; `add` only adds it. The panel
accepts standard and URL-safe Base64, with or without `=`. From PowerShell:
```powershell
$json = Get-Content .\routing.json -Raw -Encoding UTF8
$b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json))
"happ://routing/onadd/$b64"
```
The final value must stay under 8 KiB and be a single line.
### What the panel does with this JSON in JSON subscriptions
For clients that read the config from the body of a JSON subscription, the
profile is **baked into** the `dns` and `routing` sections:
- group order comes from `RouteOrder`, default `block`, `direct`, `proxy`;
- empty lists are skipped and a final "everything else → `proxy`" rule is
always appended;
- `DomainStrategy` defaults to `IPIfNonMatch`;
- DNS: a domestic server (`DomesticDNS*`, default `https://77.88.8.8/dns-query`)
is added for `DirectSites`, everything else uses `RemoteDNS*` (default
`https://8.8.8.8/dns-query`); `DnsHosts` is copied to `dns.hosts`.
Types must be exact: string is a string, a list is an array of strings,
`DnsHosts` is a string → string object. Otherwise the profile is dropped, the
subscription is served with default routing and a warning is logged.
---
## Clash / Mihomo
### Where to enter it
**Settings → Subscription → Clash / Mihomo**:
1. turn on **Enable routing**;
2. fill in **Global routing rules**, either inline or with one HTTPS URL to YAML.
The rules apply to profiles at `subClashPath` and `/mihomo/<sub-id>`. The
`/clash-legacy/` endpoint (Clash for Windows) always serves a minimal profile
and **ignores** these settings.
### What the profile already contains
The panel builds the base itself:
```yaml
proxies: # all your nodes, named by their remarks
- { name: "node-1", type: vless, ... }
proxy-groups:
- name: PROXY # select: all nodes + DIRECT
type: select
proxies: [node-1, DIRECT]
rules:
- MATCH,PROXY
```
Point your rules at the **`PROXY`** group, at `DIRECT`, at `REJECT`, or at any
group you declare yourself.
### Option 1: inline value
Three accepted forms.
**A) Plain rule lines** (`#` comments allowed):
```text
# block ads
GEOSITE,category-ads-all,REJECT
DOMAIN-SUFFIX,example.com,DIRECT
GEOIP,RU,DIRECT,no-resolve
```
**B) A YAML list:**
```yaml
- GEOSITE,category-ads-all,REJECT
- DOMAIN-SUFFIX,example.com,DIRECT
- GEOIP,RU,DIRECT,no-resolve
```
**C) A YAML map.** The `rules` key is merged with the base rules; any other key
(`proxy-groups`, `rule-providers`, `dns`, `sniffer`, …) **replaces** the
profile's key of the same name entirely:
```yaml
proxy-groups:
- name: PROXY
type: select
proxies: [DIRECT] # careful: replaces the whole PROXY group
rule-providers:
ads:
type: http
behavior: domain
format: yaml
url: https://example.com/ads.yaml
path: ./ruleset/ads.yaml
interval: 86400
rules:
- RULE-SET,ads,REJECT
- GEOIP,RU,DIRECT
```
How rules are combined:
- if your rules contain **no** `MATCH`, they are placed **before** the base
`MATCH,PROXY`, so everything else goes through the proxy;
- if a `MATCH` is present, your list **completely replaces** the base rules.
Inline validation is light: the map contents are copied as-is, so a mistake in
a group name only shows up in the client.
### Option 2: HTTPS URL to YAML
Here the panel is stricter: it **validates** the file before using it. Only
three keys are taken from the document:
| Key | Effect |
| --- | ------ |
| `rules` | Rules, merged by the same logic as above. |
| `proxy-groups` | Groups: ones with the same name replace the base ones, other base groups are kept. |
| `rule-providers` | Rule providers. |
`dns` and `sniffer` are taken **only if** the **DNS from remote rules**
(`subClashRemoteDNS`) switch is on. Enable it only for a template you trust,
since it changes the client's DNS. All other keys (`proxies`, `proxy-providers`,
`port`, …) are ignored; the nodes always stay yours.
A working example file:
```yaml
proxy-groups:
- name: Streaming
type: select
proxies: [PROXY, DIRECT]
- name: Auto
type: url-test
url: https://www.gstatic.com/generate_204
interval: 300
proxies: [PROXY]
rule-providers:
ru-direct:
type: http
behavior: domain
format: yaml
url: https://example.com/ru-direct.yaml
path: ./ruleset/ru-direct.yaml
interval: 86400
rules:
- RULE-SET,ru-direct,DIRECT
- DOMAIN-SUFFIX,netflix.com,Streaming
- GEOIP,PRIVATE,DIRECT,no-resolve
- MATCH,PROXY
```
What is checked (a failing file is rejected and the previous working version
stays):
- the document is a YAML map with at least one of `rules`, `proxy-groups`,
`rule-providers`;
- every group is a map with non-empty `name` and `type`, and names are **unique**;
- groups **cannot** use `use:` (proxy providers are not supported);
- every entry in a group's `proxies:`, every rule target and a provider's
`proxy:` must point to a group declared in the same file, to `PROXY`, or to
the built-ins `DIRECT`, `REJECT`, `REJECT-DROP`, `REJECT-TINYGIF`, `PASS`,
`GLOBAL`. A remote file is checked on its own, so the name of one of your
nodes fails the check;
- `RULE-SET,<name>,<target>` needs a provider with that name in `rule-providers`;
- each rule is a non-empty string `TYPE,value,target`; the flags `no-resolve`
and `src` may follow the target;
- size limits: 2 MiB response, plus a bound on nesting and on the size after
YAML aliases are expanded.
Node names depend on client remarks, so the most reliable target is the
**`PROXY`** group, which contains all nodes.
---
## Incy
### Where to enter it
**Settings → Subscription → Incy → Routing**:
1. turn on **Enable routing**;
2. fill in **Routing rules**:
- a ready `incy://routing/onadd/<base64>` link, the same JSON as Happ's,
Base64-encoded;
- **or one HTTPS URL** to a JSON file. The panel turns it into
`incy://autorouting/onadd/<url>` and the app **refreshes the profile
itself**.
The Incy profile goes as a line in the **body** of the subscription (only when
the User-Agent is INCY). In that case the panel does not send the `Routing`
header to Incy, so it cannot override the profile from the body.
### JSON format
The Incy profile format matches Happ's — use the same fields (`Name`,
`RouteOrder`, `DirectSites`, `DirectIp`, `ProxySites`, `BlockSites`,
`DomainStrategy`, …, see the table above):
```json
{
"Name": "RU bypass",
"GlobalProxy": "true",
"RouteOrder": "block-proxy-direct",
"DirectSites": ["geosite:private", "domain:ru", "geosite:category-ru"],
"DirectIp": ["geoip:ru", "geoip:private"],
"ProxySites": [],
"ProxyIp": [],
"BlockSites": ["geosite:category-ads-all"],
"BlockIp": [],
"DomainStrategy": "IPIfNonMatch"
}
```
Encoded form: `incy://routing/onadd/<base64 of the JSON>` (encode as in the Happ
example).
> If the Incy field is empty, Incy receives the shared **JSON subscription**
> profile (`subJsonRoutingRules`). Incy does not read the Happ field.
### The other Incy tabs
The **App**, **Banners**, **Privacy** and **Network** tabs are not routing: they
set app-management headers (profile description, banner, hidden URL,
fragmentation, …) and are sent only when **Incy header auto-detection** is on.
---
## Which format to use
| You need | Do this |
| -------- | ------- |
| One rule set for Happ and Incy | One JSON: paste as `happ://...` in Happ and `incy://...` in Incy, or give both the same HTTPS URL to the JSON. |
| Rules for Clash/Mihomo | A separate YAML; JSON and YAML are not converted into each other. |
| Change rules without touching the panel | A permanent raw URL (gist, repository) in the relevant field. |
| Check the result | Request the subscription with a client User-Agent (`curl -A "Happ/1.0"`, `-A "INCY/1.0"`, `-A "clash.meta"`) and inspect the `Routing` header / response body. |
## Common problems
- **Rules not applied, log says "Remote happ routing refresh from … failed"**
(or `clash`; for the JSON-subscription profile it says "remote source
unavailable"). The URL has not
been fetched yet (the first fetch runs in the background; refresh the
subscription in a minute) or the source returned an invalid file.
- **File rejected for size.** Happ allows 8 KiB after Base64 encoding, about
6 KiB of JSON; move long lists into
`geosite`/`geoip` categories or, for Clash, into `rule-providers`.
- **`references unknown proxy or group` error.** A rule or group points to a
name that is not in the profile. Use `PROXY`, `DIRECT`, `REJECT`, or declare
the group in the same file.
- **A gist page URL does not work.** Use the `raw` URL.
- **Clash for Windows ignores the rules.** `/clash-legacy/` does not support
custom routing; use `/mihomo/`.
+1
View File
@@ -11,6 +11,7 @@
"transports",
"clients",
"subscription",
"routing-profiles",
"share-links"
]
}
@@ -0,0 +1,411 @@
---
title: Маршрутизация для Happ, Clash/Mihomo и Incy
description: Как писать JSON и YAML профили маршрутизации для подписок — формат Happ, правила Clash/Mihomo и профиль Incy, плюс как панель их принимает и проверяет.
icon: GitBranch
---
Панель умеет отдавать клиентам готовый профиль маршрутизации: какие сайты и
IP идут напрямую, какие через прокси, а какие блокируются. Формат профиля
зависит от приложения:
| Приложение | Формат профиля | Где задаётся в панели |
| ----------------- | ------------------------------------ | ------------------------------------- |
| **Happ** | JSON (в виде `happ://` ссылки) | Настройки подписки → вкладка **Happ** |
| **Clash / Mihomo**| YAML (правила, группы, провайдеры) | Вкладка **Clash / Mihomo** |
| **Incy** | JSON (в виде `incy://` ссылки) | Вкладка **Incy** → **Маршрутизация** |
Во всех трёх полях можно указать **либо сам профиль** (inline), **либо одну
постоянную HTTPS‑ссылку** на файл — например, на raw‑gist. Ссылку удобно
использовать, чтобы менять правила, не заходя в панель.
## Как панель работает с удалённой ссылкой
В полях Happ и Clash / Mihomo значение из одной строки `https://...` считается
удалённым источником, который панель скачивает сама:
- панель скачивает файл **в фоне** и кэширует его на 10 минут; запрос подписки
никогда не ждёт источник;
- файл проверяется; если он невалиден, панель **продолжает отдавать последнее
рабочее значение** и пишет предупреждение в лог;
- допустим только `https://`, без логина/пароля в URL, адрес должен вести на
публичный хост (локальные и внутренние адреса блокируются);
- редиректы допускаются (до 5), но только на `https://`;
- лимиты: Clash — 2 МиБ; Happ — 16 КиБ ответа и 8 КиБ значения после
кодирования в Base64 (около 6 КиБ JSON); таймаут запроса 6 секунд.
Поле Incy работает иначе: панель никогда не скачивает ссылку Incy. Она только
проверяет, что это `https://` без логина/пароля, и передаёт ссылку приложению,
которое само загружает и обновляет профиль (см. раздел про Incy ниже).
Совет: используйте **raw**‑ссылку (`gist.githubusercontent.com/.../raw/...`),
а не страницу gist.
---
## Happ
### Где вводить
**Настройки → Подписка → Happ → Маршрутизация и правила**:
1. включите **Включить маршрутизацию** (заголовок `Routing-Enable: true`);
2. вставьте в поле **Правила маршрутизации** одно из:
- готовую ссылку `happ://routing/onadd/<base64>`;
- постоянную HTTPS‑ссылку на **JSON** или на файл с `happ://` ссылкой;
- `happ://routing/off` — чтобы отключить маршрутизацию на клиенте.
Панель отправляет значение клиенту в заголовке `Routing`. Если в файле по
HTTPS лежит обычный JSON, панель сама превращает его в
`happ://routing/onadd/<base64>`. Источник может также отвечать редиректом
на `happ://...` — это тоже принимается (так работают сервисы вроде
routing.help).
Если поле пустое, но заполнен **профиль маршрутизации JSON‑подписки**
(`subJsonRoutingRules`), то он же автоматически уходит в заголовок `Routing`.
Быстрее всего начать с **Пресетов маршрутизации** (Iran Bypass, China Direct,
Global, LAN bypass; опционально с блокировкой рекламы) или с
**Визуального конструктора правил** — он загружает текущий профиль и позволяет
править списки или весь JSON.
### Формат JSON
Профиль — это один JSON‑объект. Значения‑флаги Happ записывает строками
(`"true"`, `"false"`), а списки — массивами строк.
```json
{
"Name": "My Routing",
"GlobalProxy": "true",
"RouteOrder": "block-proxy-direct",
"RemoteDNSType": "DoH",
"RemoteDNSDomain": "https://cloudflare-dns.com/dns-query",
"RemoteDNSIP": "1.1.1.1",
"DomesticDNSType": "DoH",
"DomesticDNSDomain": "https://dns.alidns.com/dns-query",
"DomesticDNSIP": "223.5.5.5",
"DnsHosts": {
"cloudflare-dns.com": "1.1.1.1",
"dns.alidns.com": "223.5.5.5"
},
"DirectSites": ["geosite:private", "geosite:cn", "domain:example.cn"],
"DirectIp": ["geoip:cn", "geoip:private", "192.168.0.0/16"],
"ProxySites": [],
"ProxyIp": [],
"BlockSites": ["geosite:category-ads-all"],
"BlockIp": [],
"DomainStrategy": "IPIfNonMatch",
"FakeDNS": "false",
"UseChunkFiles": "true"
}
```
| Поле | Тип | Смысл |
| ---- | --- | ----- |
| `Name` | строка | Название профиля в приложении. |
| `GlobalProxy` | `"true"`/`"false"` | Глобальный режим: всё, что не попало в правила, идёт через прокси. |
| `RouteOrder` | строка | Порядок проверки групп через дефис: `block-proxy-direct`, `block-direct-proxy` и т. п. Побеждает **первая** сработавшая группа. Допустимые слова: `block`, `proxy`, `direct`; повторы игнорируются. |
| `DirectSites` / `ProxySites` / `BlockSites` | массив строк | Домены: напрямую / через прокси / блокировать. |
| `DirectIp` / `ProxyIp` / `BlockIp` | массив строк | IP и подсети — те же три группы. |
| `RemoteDNSDomain`, `RemoteDNSIP`, `RemoteDNSType` | строка | DNS для проксируемого трафика (`DoH` и адрес `https://.../dns-query`). |
| `DomesticDNSDomain`, `DomesticDNSIP`, `DomesticDNSType` | строка | DNS для «прямых» доменов. |
| `DnsHosts` | объект «имя → IP» | Статические записи, чтобы не резолвить DoH‑хосты через сам DNS. |
| `DomainStrategy` | строка | Стратегия Xray: `AsIs`, `IPIfNonMatch`, `IPOnDemand`. |
| `FakeDNS`, `UseChunkFiles` | `"true"`/`"false"` | Расширения Happ; панель передаёт их клиенту как есть. |
Неизвестные поля **не теряются** — панель и редактор сохраняют их и передают
Happ.
### Формат записей в списках
Записи — синтаксис Xray‑маршрутизации:
| Запись | Что совпадает |
| ------ | ------------- |
| `geosite:category-ads-all` | Категория из `geosite.dat`. |
| `geosite:private`, `geoip:private` | Локальные/приватные адреса. |
| `geoip:ir`, `geoip:cn` | Страна из `geoip.dat`. |
| `domain:example.com` | Домен и все его поддомены. |
| `full:www.example.com` | Только этот домен. |
| `keyword:ads` | Домен, содержащий подстроку. |
| `regexp:\\.ru$` | Регулярное выражение. |
| `10.0.0.0/8`, `1.2.3.4` | Подсеть CIDR или один IP. |
Запись без префикса трактуется как подстрока домена — для точности пишите
`domain:`. Категории `geosite:`/`geoip:` должны существовать в `.dat` файлах
на клиенте; панель передаёт их в заголовке `Routing`, чтобы Happ подтянул
нужные гео‑файлы.
### Как собрать `happ://` ссылку вручную
Ссылка — это префикс и JSON в Base64 (UTF‑8):
```text
happ://routing/onadd/<base64 от JSON>
```
`onadd` добавляет профиль и сразу включает его; `add` — только добавляет.
Панель принимает base64 в обычном и URL‑safe виде, с `=` и без. Из PowerShell:
```powershell
$json = Get-Content .\routing.json -Raw -Encoding UTF8
$b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json))
"happ://routing/onadd/$b64"
```
Итоговое значение не должно превышать 8 КиБ, ссылка должна быть в одну строку.
### Что панель делает с этим JSON в JSON‑подписках
Для клиентов, которые читают конфиг из тела JSON‑подписки, профиль **вшивается**
в разделы `dns` и `routing`. Правила такие:
- порядок групп — из `RouteOrder`, по умолчанию `block`, `direct`, `proxy`;
- пустые списки пропускаются, в конце всегда добавляется правило «всё остальное
→ `proxy`»;
- `DomainStrategy` по умолчанию `IPIfNonMatch`;
- DNS: для `DirectSites` добавляется «внутренний» DNS (`DomesticDNS*`, по
умолчанию `https://77.88.8.8/dns-query`), для остального — `RemoteDNS*`
(по умолчанию `https://8.8.8.8/dns-query`); `DnsHosts` копируется в `dns.hosts`.
Поля должны иметь точный тип: строка — строка, список — массив строк, `DnsHosts` —
объект «строка → строка». Иначе профиль отбрасывается и подписка отдаётся с
маршрутизацией по умолчанию (в лог пишется предупреждение).
---
## Clash / Mihomo
### Где вводить
**Настройки → Подписка → Clash / Mihomo**:
1. включите **Включить маршрутизацию**;
2. заполните **Глобальные правила маршрутизации** — inline‑текстом или одной
HTTPS‑ссылкой на YAML.
Правила применяются к профилям по адресам `subClashPath` и `/mihomo/<sub-id>`.
Эндпоинт `/clash-legacy/` (Clash for Windows) всегда отдаёт минимальный профиль
и **игнорирует** эти настройки.
### Что уже есть в профиле
Панель собирает базу сама:
```yaml
proxies: # все ваши узлы, имена — их ремарки
- { name: "node-1", type: vless, ... }
proxy-groups:
- name: PROXY # select: все узлы + DIRECT
type: select
proxies: [node-1, DIRECT]
rules:
- MATCH,PROXY
```
Ваши правила можно направлять на группу **`PROXY`**, на `DIRECT`, на `REJECT`
либо на любую группу, которую вы сами объявили.
### Вариант 1: inline‑значение
Три допустимых формы.
**А) Просто строки правил** (можно с комментариями `#`):
```text
# рекламу блокируем
GEOSITE,category-ads-all,REJECT
DOMAIN-SUFFIX,example.com,DIRECT
GEOIP,RU,DIRECT,no-resolve
```
**Б) YAML‑список:**
```yaml
- GEOSITE,category-ads-all,REJECT
- DOMAIN-SUFFIX,example.com,DIRECT
- GEOIP,RU,DIRECT,no-resolve
```
**В) YAML‑карта.** Ключ `rules` объединяется с базовыми правилами, любые другие
ключи (`proxy-groups`, `rule-providers`, `dns`, `sniffer`, …) **заменяют**
одноимённые ключи профиля целиком:
```yaml
proxy-groups:
- name: PROXY
type: select
proxies: [DIRECT] # осторожно: заменяет группу PROXY целиком
rule-providers:
ads:
type: http
behavior: domain
format: yaml
url: https://example.com/ads.yaml
path: ./ruleset/ads.yaml
interval: 86400
rules:
- RULE-SET,ads,REJECT
- GEOIP,RU,DIRECT
```
Как объединяются правила:
- если в ваших правилах **нет** `MATCH`, они ставятся **перед** базовым
`MATCH,PROXY` — всё остальное пойдёт через прокси;
- если `MATCH` есть, ваш список **полностью заменяет** базовые правила.
В inline‑режиме проверка мягкая: содержимое YAML‑карты копируется как есть,
поэтому ошибки в именах групп вы увидите только в клиенте.
### Вариант 2: HTTPS‑ссылка на YAML
Здесь панель строже — она **проверяет** файл и только затем использует.
Из документа берутся только три ключа:
| Ключ | Что делает |
| ---- | ---------- |
| `rules` | Правила — объединяются по тем же правилам, что выше. |
| `proxy-groups` | Группы: одноимённые заменяют базовые, остальные базовые сохраняются. |
| `rule-providers` | Провайдеры правил. |
Ключи `dns` и `sniffer` берутся, **только если включён** переключатель
**DNS из удалённых правил** (`subClashRemoteDNS`) — включайте его лишь для
шаблона, которому доверяете: он меняет DNS клиента. Все остальные ключи
(`proxies`, `proxy-providers`, `port` и т. д.) игнорируются. Узлы всегда
остаются вашими.
Рабочий пример файла:
```yaml
proxy-groups:
- name: Streaming
type: select
proxies: [PROXY, DIRECT]
- name: Auto
type: url-test
url: https://www.gstatic.com/generate_204
interval: 300
proxies: [PROXY]
rule-providers:
ru-direct:
type: http
behavior: domain
format: yaml
url: https://example.com/ru-direct.yaml
path: ./ruleset/ru-direct.yaml
interval: 86400
rules:
- RULE-SET,ru-direct,DIRECT
- DOMAIN-SUFFIX,netflix.com,Streaming
- GEOIP,PRIVATE,DIRECT,no-resolve
- MATCH,PROXY
```
Что обязательно проверяется (при нарушении файл отклоняется, остаётся прошлая
рабочая версия):
- документ — YAML‑карта хотя бы с одним из `rules`, `proxy-groups`,
`rule-providers`;
- каждая группа — карта с непустыми `name` и `type`, имена **уникальны**;
- в группах **нельзя** использовать `use:` (proxy‑providers не поддерживаются);
- каждая ссылка в `proxies:` группы, цель каждого правила и `proxy:` у
провайдера должны указывать на группу из этого же файла, на `PROXY` или на
встроенные `DIRECT`, `REJECT`, `REJECT-DROP`, `REJECT-TINYGIF`, `PASS`,
`GLOBAL`. Удалённый файл проверяется сам по себе, поэтому имя конкретного
узла в нём не пройдёт проверку;
- `RULE-SET,<имя>,<цель>` требует провайдера с таким именем в `rule-providers`;
- каждое правило — непустая строка вида `ТИП,значение,цель`; после цели
допускаются флаги `no-resolve` и `src`;
- ограничения размера: 2 МиБ ответа и ограничение на вложенность и объём после
разворота YAML‑алиасов.
Так как имена узлов зависят от ремарок клиентов, надёжнее всего ссылаться на
группу **`PROXY`**, которая содержит все узлы.
---
## Incy
### Где вводить
**Настройки → Подписка → Incy → Маршрутизация**:
1. включите **Включить маршрутизацию**;
2. заполните **Правила маршрутизации**:
- готовая ссылка `incy://routing/onadd/<base64>` — тот же JSON, что и у
Happ, закодированный в Base64;
- **или одна HTTPS‑ссылка** на JSON‑файл. Панель превращает её в ссылку
`incy://autorouting/onadd/<url>`, и приложение **само** периодически
перекачивает профиль.
Профиль для Incy уходит строкой в **теле** подписки (только когда User‑Agent —
INCY). Заголовок `Routing` для Incy панель в этом случае не отправляет, чтобы
он не перебил профиль из тела.
### Формат JSON
Формат профиля Incy совпадает с форматом Happ — используйте те же поля
(`Name`, `RouteOrder`, `DirectSites`, `DirectIp`, `ProxySites`, `BlockSites`,
`DomainStrategy` и т. д., см. таблицу выше):
```json
{
"Name": "RU bypass",
"GlobalProxy": "true",
"RouteOrder": "block-proxy-direct",
"DirectSites": ["geosite:private", "domain:ru", "geosite:category-ru"],
"DirectIp": ["geoip:ru", "geoip:private"],
"ProxySites": [],
"ProxyIp": [],
"BlockSites": ["geosite:category-ads-all"],
"BlockIp": [],
"DomainStrategy": "IPIfNonMatch"
}
```
Закодированная форма: `incy://routing/onadd/<base64 от JSON>` (кодирование
как в примере для Happ).
> Если поле Incy пустое, Incy получает общий профиль **JSON‑подписки**
> (`subJsonRoutingRules`). Поле Happ Incy не читает.
### Остальные вкладки Incy
Вкладки **Приложение**, **Баннеры**, **Приватность** и **Сеть** не относятся к
маршрутизации: они задают заголовки управления приложением (описание профиля,
баннер, скрытие URL, фрагментация и т. д.) и отправляются только при включённом
**Автоопределении заголовков Incy**.
---
## Какой формат выбрать
| Нужно | Решение |
| ----- | ------- |
| Один набор правил для Happ и Incy | Один JSON, вставить в Happ как `happ://...`, в Incy как `incy://...` либо дать обоим одну HTTPS‑ссылку на JSON. |
| Правила для Clash/Mihomo | Отдельный YAML. JSON и YAML взаимно не конвертируются. |
| Менять правила без правки панели | Постоянная raw‑ссылка (gist, репозиторий) в нужном поле. |
| Проверить результат | Откройте подписку клиентским User‑Agent (`curl -A "Happ/1.0"`, `-A "INCY/1.0"`, `-A "clash.meta"`) и посмотрите заголовок `Routing` / тело ответа. |
## Частые проблемы
- **Правила не применились, в логе «Remote happ routing refresh from … failed»**
(или `clash`; для профиля JSON-подписки — «remote source unavailable»).
Ссылка ещё не
скачана (первая загрузка идёт в фоне — обновите подписку через минуту) или
источник вернул невалидный файл.
- **Файл отклонён из‑за размера.** Happ — максимум 8 КиБ после кодирования в Base64
(около 6 КиБ JSON); вынесите длинные
списки в `geosite`/`geoip` категории или в `rule-providers` (Clash).
- **Ошибка `references unknown proxy or group`.** Правило или группа ссылаются
на имя, которого нет в профиле. Используйте `PROXY`, `DIRECT`, `REJECT` или
объявите группу в том же файле.
- **Ссылка на страницу gist не работает.** Нужен `raw`‑URL.
- **Clash for Windows игнорирует правила.** Эндпоинт `/clash-legacy/` не
поддерживает пользовательскую маршрутизацию — используйте `/mihomo/`.