[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
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- 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
targetand subsequent evaluation terminates. If no rules match, the traffic is handled by theFINALfallback rule. - DNS Stage Pre-matching Rejection (
pre-matching) Domain rules flagged withpre-matchingand targetingREJECTare evaluated during the DNS resolution stage. Upon matching, a rejection response (e.g., blackhole IP or empty response) is returned immediately based ondns-reject-behaviorin[General], without establishing a network connection. - Domain Resolution and IP Rules Interaction (
no-resolveoption) IP-based rules (e.g.,IP-CIDR,GEOIP) normally initiate DNS queries to obtain IPs when evaluating domain requests. When theno-resolveoption 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:
# 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 atarget.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 HTTP200 OKwith 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.
URL-REGEX,"^https://example\.com/(a|b)?k=v$",ProxyGroup
USER-AGENT,"ExampleClient/1.0 (macOS, arm64)",DIRECT
SCRIPT,"Rule Judge (v2)",ProxyGroupRule 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: Integer1–65535) Matches the destination connection port number.SRC-PORT(Match value: Integer1–65535) Matches the local client source port number.PROTOCOL(Alias:NETWORK; Match value:TCP,UDP,HTTP,HTTPS,QUIC, orSTUN; values are case-insensitive)TCPandUDPmatch all traffic on that transport, including recognized application protocols. Other values match the identified application protocol.NETWORKhas the same semantics asPROTOCOL, and canonical formatting outputsPROTOCOL. 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 offersh2orhttp/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.
iniPROTOCOL,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 theUser-Agentheader in HTTP requests.
Script Rules
SCRIPT(Match value: Name of atype=rulescript declared in[Script]within the same profile) Syntax:SCRIPT,name,policy[,requires-resolve]. The script inspects$requestand calls$done({matched: true})or$done({matched: false})to return matching results; the outbound action on match is taken frompolicyin 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-resolveis 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.SCRIPTreferences merged from profiles and plugins must exist and point totype=rule, or configuration validation fails. External rule resources are loaded at runtime; missing references, unavailable script resources, execution errors, or timeouts treat the condition asfalse, logging warnings before continuing.SCRIPTcan be nested inAND,OR,NOTfollowing standard boolean logic; note thatNOT(SCRIPT)will invert an error-inducedfalsetotrue.iniSCRIPT,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:DOMAINandDOMAIN-SUFFIXentries representable in a domain set are written to the shared DomainSet store, reusing domain lookup results within the same routing evaluation;DOMAIN-SUFFIX,example.commatches both the apex domain and its subdomains.IP-CIDR/IP-CIDR6andSRC-IP-CIDRentries 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 carryno-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.- 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-SETobtains collection handles viaget(id)on each store at load time; multiple references to the same resource share a single load and update cycle. Prebuilt files reside underprebuild/in the resource cache directory and contain onlyip.mmdband order-preservingother.list(with resolution options recorded in comment headers). Startup uses the existing domain database and MMDB directly and only parsesother.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-SETrule line carriesno-resolve, active DNS resolution is skipped for that evaluation (and sub-rules such asSCRIPTwithrequires-resolveare prevented from triggering resolution), while traffic whose destination is already an IP or was resolved by an earlier rule still evaluates normally; separateRULE-SETlines referencing the same resource can configureno-resolveindependently.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 theFINALrule.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 tofalse) Applicable to IP-based rules and rule sets (IP-CIDR,GEOIP,IP-ASN,RULE-SET, etc.). When set totrue(or specified simply asno-resolve), if the target is a domain name that has not yet resolved to an IP, DNS resolution is skipped (forIP-CIDR/GEOIP/IP-ASN, the rule is skipped; forRULE-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.iniIP-CIDR,10.0.0.0/8,DIRECT,no-resolve RULE-SET,https://rules.example.com/list.txt,DIRECT,no-resolverequires-resolve(Boolean or standalone flag, defaultfalse) Used only forSCRIPT. 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.iniSCRIPT,judge,DIRECT,requires-resolvepre-matching(Boolean or standalone flag, defaultfalse) Applicable to domain rules (DOMAIN,DOMAIN-SUFFIX,DOMAIN-KEYWORD,DOMAIN-WILDCARD,DOMAIN-SET) with the target strictly set to built-inREJECT. When enabled, the rule is registered into the DNS pre-matching table to block queries during DNS resolution.iniDOMAIN-SUFFIX,ad.example.com,REJECT,pre-matchingupdate-interval(Integer, unit: seconds, default86400) 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 to86400seconds when unset; setting<= 0(such as0or-1) disables scheduled and background auto-updates (a missing local cache is still fetched once, and manual refreshes are unaffected).iniDOMAIN-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:
- Execution Timing: Every DNS query evaluates rules flagged with
pre-matchingbefore 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. - Response Behavior: When matched, DNS resolution terminates immediately and returns a response configured by
dns-reject-behaviorin General.
Configuration Examples
Basic Configuration
[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