Skip to content

[Rule] Traffic Routing Rules ​

This section configures traffic routing policies, evaluating network requests sequentially from top to bottom and dispatching them to designated targets or outbounds (direct, reject/drop, proxy servers, or policy groups).

Matching Workflow ​

text
Inbound Network Request
    │
    ▼
┌─────────────────────────┐
│ DNS Pre-matching Reject │  ──(matches pre-matching & REJECT)──► Returns reject response per dns-reject-behavior
│ (pre-matching)          │
└───────────┬─────────────┘
            │ No match
            ▼
┌─────────────────────────┐
│ Sequential Rule Match   │
│ (Top-to-bottom, first   │
│  match wins)            │
└───────────┬─────────────┘
            ├─────────────────────────────────────────────────┐
            ▼                                                 ▼
    Matches Domain / Port / Protocol rules             Encountered IP rule (IP-CIDR / GEOIP, etc.)
            │                                                 │
            │                                           ┌─────┴─────────────────┐
            │                                           │ Contains no-resolve ? │
            │                                           └─────┬─────────────────┘
            │                                      Yes (skip match)│   │ No (triggers DNS resolution)
            │                                           ┌─────┘   ▼
            │                                           │    Obtains real target IP
            │                                           │         │
            │                                           │    Matches target IP subnet
            │                                           │         │
            ▼                                           ▼         ▼
      Execute designated target action ◄──────────────────────────────┘
            │
            ▼ (No rules matched)
      Execute FINAL fallback routing policy
  1. Top-to-Bottom First-Match-Wins The rule table evaluates sequentially starting from the first line. Once a request matches a rule, it is immediately dispatched to the specified target and subsequent evaluation terminates. If no rules match, the traffic is handled by the FINAL fallback rule.
  2. DNS Stage Pre-matching Rejection (pre-matching) Domain rules flagged with pre-matching and targeting REJECT are evaluated during the DNS resolution stage. Upon matching, a rejection response (e.g., blackhole IP or empty response) is returned immediately based on dns-reject-behavior in [General], without establishing a network connection.
  3. Domain Resolution and IP Rules Interaction (no-resolve option) IP-based rules (e.g., IP-CIDR, GEOIP) normally initiate DNS queries to obtain IPs when evaluating domain requests. When the no-resolve option is appended, the rule is skipped without triggering DNS resolution if the request does not yet have a resolved IP.

Syntax Declaration ​

Rules in [Rule] are declared as standard rules, composite logical rules, or fallback rules:

ini
# Standard rule
TYPE, match_value, target, [options...]

# Composite logical rules
AND|OR, ((sub-rule-1), (sub-rule-2), ...), target, [options...]
NOT, ((sub-rule)), target, [options...]

# Fallback rule
FINAL, target, [options...]

Syntax Elements ​

  • TYPE: Rule matching type in uppercase English letters (e.g., DOMAIN-SUFFIX, IP-CIDR).
  • match_value: Rule condition value. Depending on the type, this can be a domain, IP CIDR, port number, country code, or external resource URL.
  • sub-rule: Sub-rule definition within composite logical rules, formatted as (TYPE, match_value, [options...]), without a target.
  • target: Routing destination upon matching. Supports the following built-in basic policies, proxy servers defined in Proxy, and policy groups defined in Proxy Group:
    • DIRECT: Direct connection without proxying.
    • REJECT: Rejects connection (returns HTTP 503 for HTTP, sends connection reset or close for TCP/UDP).
    • REJECT-TINYGIF: Returns HTTP 200 OK with a 1×1 transparent GIF for HTTP requests; sends connection reset or close for TCP/UDP.
    • REJECT-DROP: Silently drops traffic without replying (holds HTTP connections until timeout).
    • REJECT-NO-DROP: Immediate rejection without converting to silent drop.
  • options: Optional parameter list separated by commas, supporting key-value pairs and standalone boolean flags.

Quoting and Special Characters ​

When a rule's match_value (such as URL-REGEX or USER-AGENT containing parameters or special characters), SCRIPT name, or target contains commas (,), equals signs (=), leading or trailing whitespace, inline comment triggers (whitespace followed by # or ;), or starts with (, ), [, ], {, }, #, or ;, enclose it in double quotes "...". Inside double quotes, escape embedded double quotes as \" and backslashes as \\. Inside AND, OR, or NOT sub-rule parentheses, also quote any argument containing container delimiters.

ini
URL-REGEX,"^https://example\.com/(a|b)?k=v$",ProxyGroup
USER-AGENT,"ExampleClient/1.0 (macOS, arm64)",DIRECT
SCRIPT,"Rule Judge (v2)",ProxyGroup

Rule Types Reference ​

Domain Rules ​

  • DOMAIN (Match value: Exact domain string, e.g., example.com) Exact and complete domain match.
  • DOMAIN-SUFFIX (Match value: Domain suffix string, e.g., apple.com) Matches the domain itself and all its subdomains (e.g., api.apple.com).
  • DOMAIN-KEYWORD (Match value: Keyword substring, e.g., google) Matches if the keyword appears anywhere within the domain name.
  • DOMAIN-WILDCARD (Match value: Wildcard pattern, e.g., *.cdn.*.com) Supports * (zero or more characters) and ? (single character) wildcard matching.
  • DOMAIN-SET (Match value: Local file path or HTTP/HTTPS URL) Imports an external plain-text domain list with one domain rule per line. IP entries are skipped; domain sets are not queried when the target is an IP address.

IP and Geolocation Rules ​

  • IP-CIDR (Match value: IPv4 or IPv6 CIDR subnet, e.g., 192.168.1.0/24) Matches if the target server IP falls within the specified subnet.
  • IP-CIDR6 (Match value: IPv6 CIDR subnet, e.g., 2001:db8::/32) Dedicated IPv6 destination subnet matching.
  • SRC-IP-CIDR (Match value: IPv4 or IPv6 CIDR subnet, e.g., 10.0.0.0/8) Matches the source client IP initiating the connection.
  • GEOIP (Match value: Two-letter ISO country/region code, e.g., CN, US) Determines destination IP geolocation using built-in or downloaded GeoIP databases.
  • IP-ASN (Match value: Positive integer ASN, e.g., 15169) Matches the Autonomous System Number (ASN) of the target IP.

Port and Protocol Rules ​

  • DEST-PORT (Match value: Integer 1–65535) Matches the destination connection port number.

  • SRC-PORT (Match value: Integer 1–65535) Matches the local client source port number.

  • PROTOCOL (Alias: NETWORK; Match value: TCP, UDP, HTTP, HTTPS, QUIC, or STUN; values are case-insensitive) TCP and UDP match all traffic on that transport, including recognized application protocols. Other values match the identified application protocol. NETWORK has the same semantics as PROTOCOL, and canonical formatting outputs PROTOCOL. Rules use first-match order; place specific application protocols before broad transport rules.

    TCP inspection happens at ingress after matching the known destination against always-raw-tcp-hostname. Matching hosts skip inspection; all other TCP connections are inspected only on ports 80 and 443. Other ports do not trigger reads. Sniffed SNI is stored separately and takes priority when matching takeover lists without rewriting the original destination. UDP datagrams are inspected and buffered at ingress within a bounded budget. Protocol rules use existing metadata from ingress or normal request parsing and never trigger reads. HTTP request lines and the HTTP/2 preface identify HTTP. TLS ClientHello is heuristically classified as HTTPS only when its ALPN offers h2 or http/1.1; TLS or SNI alone does not establish HTTPS. After MITM, negotiated ALPN and normal HTTP parsing determine the protocol, while request-level classification follows the URL scheme.

    Ingress inspection has a total 200 ms budget. HTTP is limited to 8 KiB and TLS to 64 KiB. The discriminator is read first, and TLS reads follow record boundaries. UDP observes at most four complete datagrams, continuing only for an inconclusive QUIC candidate so that a later Initial can provide evidence. Inspection stops when the protocol is identified or ruled out. Buffered data is replayed intact. Inconclusive results and timeouts retain the original TCP/UDP classification; I/O errors terminate the connection. Routing never re-inspects traffic. HTTP processing and MITM still require their respective policy lists and protocol evidence.

    ini
    PROTOCOL,QUIC,REJECT
    PROTOCOL,STUN,DIRECT
    PROTOCOL,HTTPS,Proxy
    PROTOCOL,TCP,DIRECT
    PROTOCOL,UDP,DIRECT

Application-Layer HTTP Rules ​

Application-layer rules rely on plaintext HTTP request contents. For non-HTTP traffic or HTTPS traffic not decrypted via MITM, these rules are automatically skipped and evaluated by subsequent rules.

  • URL-REGEX (Match value: Regular expression) Matches the complete HTTP request URL (including path and query parameters).
  • USER-AGENT (Match value: Pattern string, supports wildcards) Matches the User-Agent header in HTTP requests.

Script Rules ​

  • SCRIPT (Match value: Name of a type=rule script declared in [Script] within the same profile) Syntax: SCRIPT,name,policy[,requires-resolve]. The script inspects $request and calls $done({matched: true}) or $done({matched: false}) to return matching results; the outbound action on match is taken from policy in the rule line, rather than decided by the script. Rule scripts use QuickJS by default; refer to Script for environment variables and APIs.

    Within the same routing evaluation, repeated references to the same script reuse the first execution result; distinct requests evaluate independently. When requires-resolve is not specified, domain names are not proactively resolved; when specified, the target address is resolved first and IPv4/IPv6 addresses are provided via $request.dnsResult. Pre-matching is forbidden on rule scripts.

    SCRIPT references merged from profiles and plugins must exist and point to type=rule, or configuration validation fails. External rule resources are loaded at runtime; missing references, unavailable script resources, execution errors, or timeouts treat the condition as false, logging warnings before continuing. SCRIPT can be nested in AND, OR, NOT following standard boolean logic; note that NOT(SCRIPT) will invert an error-induced false to true.

    ini
    SCRIPT,judge,DIRECT
    SCRIPT,"Rule Judge (v2)",ProxyGroup,requires-resolve

External Rule Sets ​

  • RULE-SET (Match value: Local file path or HTTP/HTTPS URL) Imports an external rule file where each line defines a rule without a target policy; matched traffic uses the target policy of the referencing line. Rules are indexed upon loading with a fixed matching order:

    1. DOMAIN and DOMAIN-SUFFIX entries representable in a domain set are written to the shared DomainSet store, reusing domain lookup results within the same routing evaluation; DOMAIN-SUFFIX,example.com matches both the apex domain and its subdomains.
    2. IP-CIDR / IP-CIDR6 and SRC-IP-CIDR entries are compiled by the GeoIP store into one standard MMDB file per resource, recording address family, target/source direction, and merged overlapping subnet flags, then memory-mapped (mmap) directly for lookup without rebuilding an IP tree from source text. When all destination CIDRs carry no-resolve, domains are not proactively resolved; otherwise, DNS resolution runs on demand after the domain set misses and reuses any addresses already resolved during the current routing pass.
    3. Keywords, wildcards, regular expressions, composite logical rules, and other rules retain their original order and are evaluated sequentially, with logical combinations preserving their native semantics.

    Once the domain set or IP tree matches, subsequent rules are skipped. The original line order in the resource file does not dictate precedence across these three groups, while rules within the remaining sequential list continue to short-circuit in original order. RULE-SET obtains collection handles via get(id) on each store at load time; multiple references to the same resource share a single load and update cycle. Prebuilt files reside under prebuild/ in the resource cache directory and contain only ip.mmdb and order-preserving other.list (with resolution options recorded in comment headers). Startup uses the existing domain database and MMDB directly and only parses other.list, without re-importing domains.

    If a domain target still has no resolved IP, destination IP rules are skipped; source IP rules evaluate independently. When the referencing RULE-SET rule line carries no-resolve, active DNS resolution is skipped for that evaluation (and sub-rules such as SCRIPT with requires-resolve are prevented from triggering resolution), while traffic whose destination is already an IP or was resolved by an earlier rule still evaluates normally; separate RULE-SET lines referencing the same resource can configure no-resolve independently.

  • RULE-SET-LEGACY (Match value: Local file path or HTTP/HTTPS URL) Imports an external rule file and evaluates rules sequentially in their original file order, using the referencing line's target policy on match.

Both rule set types share the resource caching and update mechanism. RULE-SET streams builds into a temporary directory inside a domain transaction, atomically switches the prebuilt directory once files are verified, and then commits the transaction and publishes lookup data; failures before commit restore the previous cache and continue serving the last active data. Missing prebuild directories trigger a rebuild from source, while corrupted caches report load failures; consistency between files and the domain database after an abnormal exit is not verified.

Composite Logical Rules ​

Composite rules perform multi-dimensional combined matching evaluations. Sub-rules must be enclosed within double parentheses ((...)) separated by commas:

  • AND (Syntax: AND, ((sub_rule_1), (sub_rule_2), ...), target) Matches when all contained sub-rules evaluate to true.
  • OR (Syntax: OR, ((sub_rule_1), (sub_rule_2), ...), target) Matches when any contained sub-rule evaluates to true.
  • NOT (Syntax: NOT, ((sub_rule)), target) Contains a single sub-rule; matches when the sub-rule does not match.

Fallback and System Rules ​

  • FINAL (Match value: None, specify target directly) Matches all remaining traffic not caught by preceding rules as the final exit. When appending rules via plugins or external configurations (%APPEND%), new rules are always inserted before the FINAL rule.
  • PROCESS-NAME (Match value: Process name string) Reserved configuration item; acts as a placeholder in the current version.

Rule Options ​

Rule lines can append optional configuration options after the target field:

  • no-resolve (Boolean or standalone flag, default unset / equivalent to false) Applicable to IP-based rules and rule sets (IP-CIDR, GEOIP, IP-ASN, RULE-SET, etc.). When set to true (or specified simply as no-resolve), if the target is a domain name that has not yet resolved to an IP, DNS resolution is skipped (for IP-CIDR/GEOIP/IP-ASN, the rule is skipped; for RULE-SET, active DNS resolution is skipped while domain and non-IP rules still evaluate). If the target is already an IP or has been resolved by a preceding rule, matching proceeds normally.

    ini
    IP-CIDR,10.0.0.0/8,DIRECT,no-resolve
    RULE-SET,https://rules.example.com/list.txt,DIRECT,no-resolve
  • requires-resolve (Boolean or standalone flag, default false) Used only for SCRIPT. Proactively resolves domains and provides $request.dnsResult; uses the raw IP if the target is already an IP address. When composite rules or external resources contain sub-rules requiring resolution, they share the same DNS resolution result. Repeated references to the same script still reuse the initial result.

    ini
    SCRIPT,judge,DIRECT,requires-resolve
  • pre-matching (Boolean or standalone flag, default false) Applicable to domain rules (DOMAIN, DOMAIN-SUFFIX, DOMAIN-KEYWORD, DOMAIN-WILDCARD, DOMAIN-SET) with the target strictly set to built-in REJECT. When enabled, the rule is registered into the DNS pre-matching table to block queries during DNS resolution.

    ini
    DOMAIN-SUFFIX,ad.example.com,REJECT,pre-matching
  • update-interval (Integer, unit: seconds, default 86400) Applicable to external resource rules (DOMAIN-SET, RULE-SET, RULE-SET-LEGACY). Specifies the background update interval for the resource. Remote HTTP/HTTPS resources default to 86400 seconds when unset; setting <= 0 (such as 0 or -1) disables scheduled and background auto-updates (a missing local cache is still fetched once, and manual refreshes are unaffected).

    ini
    DOMAIN-SET,https://rules.example.com/ad-domains.txt,REJECT,pre-matching,update-interval=86400

DNS Pre-matching Reject Mechanism ​

Domain rules with the pre-matching option (and target REJECT) perform pre-matching during the DNS resolution stage:

  1. Execution Timing: Every DNS query evaluates rules flagged with pre-matching before reusing or allocating Fake-IPs or querying upstream resolvers. Existing or restored persistent mappings do not bypass pre-matching; when a DOMAIN-SET updates, subsequent queries evaluate against the updated content. Pre-matching interception takes precedence over global direct or global proxy modes.
  2. Response Behavior: When matched, DNS resolution terminates immediately and returns a response configured by dns-reject-behavior in General.

Configuration Examples ​

Basic Configuration ​

ini
[General]
dns-reject-behavior = blackhole

[Proxy]
ProxyNode = socks, 198.51.100.1, 1080
DirectOut = direct

[Proxy Group]
AutoProxy = url-test, ProxyNode, DirectOut, check-interval=300
Streaming = select, ProxyNode, DirectOut

[Rule]
# 1. DNS pre-matching reject rules
DOMAIN-SUFFIX,ad.example.com,REJECT,pre-matching
DOMAIN-KEYWORD,telemetry,REJECT,pre-matching
DOMAIN-SET,https://rules.example.com/ad-domains.txt,REJECT,pre-matching,update-interval=86400

# 2. Local and LAN direct rules
DOMAIN-SUFFIX,local,DIRECT
IP-CIDR,10.0.0.0/8,DIRECT,no-resolve
IP-CIDR,172.16.0.0/12,DIRECT,no-resolve
IP-CIDR,192.168.0.0/16,DIRECT,no-resolve
IP-CIDR,127.0.0.0/8,DIRECT,no-resolve

# 3. Dedicated streaming group rules
DOMAIN-SUFFIX,media.example.com,Streaming
DOMAIN-SUFFIX,video.example.com,Streaming

# 4. Composite logical and quoted special-character rules
AND,((DOMAIN-SUFFIX,internal.example.com),(DEST-PORT,443)),DIRECT
URL-REGEX,"^https://example\.com/(a|b)?k=v$",AutoProxy
USER-AGENT,"ExampleClient/1.0 (macOS, arm64)",DIRECT

# 5. External rule set reference
RULE-SET,./rules/custom.list,AutoProxy,update-interval=43200

# 6. Geolocation and fallback policies
GEOIP,CN,DIRECT
FINAL,AutoProxy