Clash Rule Providers: Advanced GitHub Automation Guide
Design the Rule Provider Architecture Before Writing Automation
Rule providers are external rule collections that Clash or Mihomo downloads and loads separately from the main YAML configuration. They are useful when a domain list changes frequently, when several devices should share the same routing data, or when the main configuration would become difficult to review. A provider can contain domain rules, IP-CIDR rules, or classical rule objects, while the main configuration only defines how that provider is fetched and which policy group should handle matching traffic.
A reliable automation design separates four responsibilities: source data, transformation, validation, and publication. Source data may be a manually reviewed text file, an upstream list, or a set of generated entries. Transformation converts that input into the format expected by Clash. Validation checks syntax, duplicates, unsupported entries, and accidental empty output. Publication makes the final file available over HTTPS with a stable URL. GitHub Actions can coordinate these stages, but the workflow should not be treated as a substitute for configuration design.
The most important boundary is between a rule provider and the rules section. A provider does not decide its own final policy. The main configuration references the provider with a rule such as RULE-SET,provider-name,Proxy. The provider supplies matching data, while the rule line determines the target proxy group. This separation allows the same list to be routed through different policies in different profiles.
Provider data
The generated file containing domain, IP-CIDR, or classical rules. It should be deterministic, readable, and independently testable.
Provider definition
The YAML object that declares the provider type, URL, local cache path, format, and refresh interval.
Provider reference
The RULE-SET entry in the main rules list that connects provider matches to a proxy group.
Choose a Stable Provider Format and Naming Scheme
Clash-compatible cores commonly support different provider behaviors. A domain provider is appropriate when the list contains domain names or domain suffixes. An IP-CIDR provider is intended for network ranges and may require a no-resolve decision in the consuming rule, depending on how DNS and matching are configured. A classical provider can contain complete rule lines such as domain, IP-CIDR, process-name, or other supported rule types. The correct choice depends on the information available in the source list, not on which format is easiest to generate.
For a domain provider, a YAML payload may look like this:
payload:
- '+.example-a.test'
- '+.example-b.test'
- 'service.example-c.test'
The leading +. convention is commonly used to represent a domain and its subdomains in Clash-compatible domain matching. Do not add it blindly to every input. An entry that is already an exact host, an IP address, a CIDR range, or a wildcard expression may require a different rule type. The automation should normalize known input forms rather than applying a single text replacement to all lines.
A provider definition in the main configuration can follow this structure:
rule-providers:
company-domains:
type: http
behavior: domain
format: yaml
url: https://example.invalid/providers/company-domains.yaml
path: ./providers/company-domains.yaml
interval: 86400
rules:
- RULE-SET,company-domains,CompanyProxy
- MATCH,Default
The exact supported fields can vary between the original Clash family and maintained Mihomo-based cores. Check the running core’s documentation and startup log when a field is ignored. In particular, do not assume that a GUI client’s configuration editor validates every provider option. A client may accept the YAML visually while its bundled core rejects the provider during loading.
Names should be short, descriptive, and stable. Prefer names such as streaming-domains, work-cidr, or research-sites over names that contain dates or release numbers. If a provider name changes every time the list is rebuilt, all consuming configurations must be edited. Dates belong in generated metadata or release notes, not in the identifier used by RULE-SET.
| Provider type | Typical content | Best use | Common mistake |
|---|---|---|---|
| Domain | Domain names and suffixes | Website categories and service domains | Putting IP addresses into a domain-only list |
| IP-CIDR | IPv4 or IPv6 network ranges | Known address ranges and private routing | Forgetting DNS-resolution implications |
| Classical | Complete Clash rule expressions | Mixed rule types and advanced matching | Generating invalid or unsupported rule syntax |
Build a Reusable GitHub Actions Workflow
A production workflow should run for a scheduled refresh, a manual dispatch, and a change to source files. Scheduled execution handles upstream changes, manual execution helps recover from a failed publication, and source-based execution gives immediate feedback when a pull request modifies the list generator. These triggers serve different purposes and should not be replaced by a single daily schedule.
A minimal workflow can be organized into checkout, setup, generation, validation, and publication stages:
name: Build rule providers
on:
workflow_dispatch:
schedule:
- cron: "17 3 * * *"
push:
paths:
- "sources/**"
- "scripts/**"
- ".github/workflows/providers.yml"
permissions:
contents: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Check out source
uses: actions/checkout@v4
- name: Set up runtime
uses: actions/setup-python@v5
with:
python-version: "3.x"
- name: Generate providers
run: python scripts/build_providers.py
- name: Validate providers
run: python scripts/validate_providers.py providers/
- name: Show changes
run: git diff -- providers/
- name: Publish changes
run: |
git config user.name "rule-provider-bot"
git config user.email "[email protected]"
git add providers/
git diff --cached --quiet || git commit -m "Update generated providers"
git push
The example is intentionally generic. Pin action versions according to the maintenance policy of the repository, and consider pinning to immutable commit references when the workflow is used in a sensitive environment. The workflow needs write permission only when it commits generated files back to the repository. If the repository publishes artifacts through another mechanism, use the smallest permission set that supports that mechanism.
Do not place subscription URLs, private access tokens, node credentials, or controller secrets in provider files. A rule provider normally contains routing data, not credentials. If a private source must be downloaded, store the credential as an encrypted repository secret and pass it to the generation process without printing it. Generated output should also be checked for accidental URLs, tokens, or private hostnames before publication.
Deterministic output is essential. Sort entries using a documented rule, normalize line endings, remove comments only when the comments are not meaningful, and write a final newline. If the same input produces a different file on every run, reviewers cannot distinguish real rule changes from formatting noise. Stable output also improves caching and makes rollback easier.
Schedule Updates Without Creating Repository Noise
A scheduled job should commit only when the generated content changes. The git diff --cached --quiet check in the example prevents empty commits, but it does not prevent a source that changes ordering every time from producing unnecessary updates. Sort the input before generating output, remove duplicate entries, and keep volatile timestamps outside the provider payload whenever possible.
Choose the schedule based on how quickly the source changes and how aggressively clients refresh. A provider updated hourly is not useful if every client downloads it once per day. Conversely, a daily provider may be sufficient for a stable corporate network range. Avoid setting a very short client-side interval merely because the workflow runs frequently; repeated downloads increase load and can cause rate limits or unnecessary startup delays.
Hands-On Build and Test Procedure
The following procedure creates a repeatable path from source data to a provider that can be consumed by a Clash or Mihomo profile. Run it in a test branch first, especially when the provider will affect many devices.
- Define the input contract. Decide whether the source accepts exact domains, suffixes, CIDR ranges, comments, blank lines, or complete rule expressions. Document one example of every accepted form.
- Normalize the input. Trim surrounding whitespace, convert line endings, ignore approved comments, remove duplicates, and reject malformed entries instead of silently dropping them.
- Generate the payload. Write the selected format to a stable filename such as
providers/streaming-domains.yaml. Keep the output structure minimal and use consistent quoting. - Validate syntax. Parse the resulting YAML with a YAML parser. Then inspect the payload type, entry count, and representative entries. A syntactically valid YAML file can still contain the wrong provider behavior.
- Test references. Confirm that the main configuration uses the exact provider name and that the target policy group exists. A provider can load successfully while its
RULE-SETline points to a misspelled group. - Publish and fetch. After the workflow completes, retrieve the public file from its final HTTPS address. Verify the response status, content type, file body, and whether redirects are accepted by the running core.
- Load in a test client. Reload the profile, open the provider status page if the client exposes one, and check the update timestamp or download log. Do not test only by opening a previously cached website.
- Verify rule priority. Test one domain that should match the provider, one domain that should bypass it through an earlier rule, and one unrelated domain that should reach the fallback rule.
During testing, clear or refresh the provider cache only when necessary. A cached copy can make a broken publication appear healthy, while deleting the cache too early can remove the last known-good data. Keep a known-good local copy and compare its checksum or entry count with the downloaded version.
Control Rule Priority, Cache Behavior, and Rollbacks
Clash evaluates the main rules list from top to bottom. A provider rule placed below a broad rule may never receive traffic. For example, an earlier DOMAIN-SUFFIX,example.test,DIRECT entry takes precedence over a later provider entry containing the same domain. Likewise, a broad GEOIP, MATCH, or process rule can make a provider appear empty even when it loaded correctly.
Arrange rules from specific exceptions to broader categories, then place the final fallback at the end:
rules:
- DOMAIN,login.example.test,DIRECT
- RULE-SET,work-domains,WorkProxy
- RULE-SET,work-cidr,WorkProxy
- GEOIP,PRIVATE,DIRECT,no-resolve
- MATCH,Default
Use the connection log to distinguish provider problems from priority problems. If a connection log shows an earlier rule, the provider is not necessarily broken. If the provider is absent from the provider list or the log reports a download or parse error, investigate the provider definition and publication. If the provider is loaded and selected but the connection fails, investigate the target proxy group, DNS result, or upstream node separately.
Provider caching has two useful roles. First, the local path gives the core a reusable copy, reducing the need to download the file on every restart. Second, a last-known-good copy can preserve routing behavior during a temporary hosting outage. Caching is not a reason to publish unstable files, however. Use atomic generation and publication where possible so clients do not fetch a partially written document.
When a generated list is wrong, rollback should be straightforward. Restore the previous provider file, rerun validation, and publish it as a normal change. Do not change the provider name or rewrite every consuming profile during an emergency unless the format itself is unsafe. A stable URL and stable identifier allow the rollback to propagate through the existing update mechanism.
| Symptom | Likely layer | First check |
|---|---|---|
| Provider download fails | Hosting or network | HTTPS status, certificate, redirects, and final URL |
| Provider parses but never matches | Rules or data type | Behavior, entry syntax, and rule order |
| Provider is always old | Cache or refresh interval | Local path, update timestamp, and client interval |
| Workflow changes every run | Generator | Sorting, duplicates, timestamps, and line endings |
Production Troubleshooting and Maintenance
Start troubleshooting by identifying the failing layer instead of changing several settings simultaneously. A workflow failure belongs to generation or publication. A provider load failure belongs to the client, core, URL, or YAML format. A provider that loads but routes incorrectly belongs to data semantics or rule priority. A correctly routed connection that cannot open belongs to DNS, the proxy group, the selected node, or the destination service.
Check the action log for the first meaningful error, not only the final failed step. A parser error may be followed by a misleading “file not found” message because the generation stage never created the expected output. Add explicit checks for file existence and non-zero entry counts. A provider with zero entries may be valid YAML but operationally dangerous because traffic falls through to later rules.
HTTP hosting problems are also common. A browser may display a file after following redirects, while a core version or embedded downloader handles redirects differently. Prefer a stable HTTPS endpoint without authentication unless private distribution is required. Confirm that the server returns the actual provider content rather than an HTML error page, access-denied document, or repository landing page.
Review compatibility after changing the running core. Mihomo may support provider features that an older Clash core does not, while a GUI may expose fields that only its bundled core understands. Keep a small compatibility matrix for the clients in use: core family, version, provider behavior, file format, TUN status, and refresh result. This is more useful than recording only the GUI application name.
Finally, treat rule providers as code. Use pull requests for source changes, require validation before merging, review large entry-count changes, and retain enough history to identify when a domain or CIDR disappeared. Limit automated updates to the files they are expected to modify. A clear repository layout might contain sources/ for reviewed inputs, scripts/ for generators and validators, providers/ for published files, and .github/workflows/ for automation.
Frequently Asked Questions
Should a rule provider contain domains or complete RULE-SET lines?
Use a domain provider when the data is a domain list and an IP-CIDR provider when the data is a network list. Use a classical provider when the source intentionally contains complete rule expressions or several rule types. The consuming configuration must declare the matching behavior correctly; otherwise valid entries may not match as expected.
Why does the provider download successfully but traffic use the wrong proxy?
Successful loading only proves that the provider was fetched and parsed. Clash still evaluates the main rules from top to bottom. Inspect the connection log for the actual matched rule, then look for an earlier broad rule, a misspelled provider name, or a target proxy group that does not select the intended node.
How often should GitHub Actions rebuild a provider?
Choose a schedule based on source volatility and the refresh interval used by clients. Daily updates are enough for slowly changing lists, while frequently changing security or service data may need a shorter interval. Avoid generating identical commits and avoid client refresh intervals that create unnecessary download traffic.
Can a cached provider keep working during a hosting outage?
Usually, a previously downloaded local copy can continue to be used, depending on the core and client behavior. Do not assume this without testing. Keep the provider path stable, monitor update logs, and retain a known-good published version so an outage or bad generation can be rolled back quickly.