ClashX Advanced Usage Tips: Unleash the Full Potential of Your Proxy Tool

ClashX advanced usage tips cover

Introduction: Advanced Tips Overview

After mastering the basic usage of ClashX, the next step is to learn how to fully harness the potential of this powerful tool. Advanced techniques not only improve proxy performance but also create more flexible and intelligent network routing solutions.

This article systematically introduces advanced ClashX usage methods, including smart routing, automation scripts, performance tuning, rule optimization, and other professional techniques. These tips are suitable for advanced users who already have some ClashX usage experience.

💡
Advanced Users Must Read

After mastering these techniques, you will be able to create fully customized proxy solutions, improve network performance, and handle various complex network scenarios.

Smart Routing Strategies

The core of smart routing is to route traffic to different proxy nodes or direct connections based on different traffic characteristics (domain names, IPs, geographic locations, etc.). This optimizes performance, reduces latency, and bypasses regional restrictions.

Complex Domain-Based Routing

routing

rules:
  # Line Level 1:Whitelist Direct(Highest Priority)
  - DOMAIN,localhost,DIRECT
  - DOMAIN-SUFFIX,local,DIRECT
  - DOMAIN-SUFFIX,lan,DIRECT

  # Line Level 2:Domestic Services Direct
  - DOMAIN-SUFFIX,alipay.com,DIRECT
  - DOMAIN-SUFFIX,baidu.com,DIRECT
  - DOMAIN-SUFFIX,taobao.com,DIRECT
  - DOMAIN-SUFFIX,qq.com,DIRECT

  # Line Level 3:Global Streaming
  - DOMAIN-SUFFIX,netflix.com,🎬 Streaming
  - DOMAIN-SUFFIX,youtube.com,🎬 Streaming
  - DOMAIN-SUFFIX,twitch.tv,🎬 Streaming
  - DOMAIN-KEYWORD,spotify,🎬 Streaming

  # Line Level 4:Gaming Acceleration
  - DOMAIN-SUFFIX,epicgames.com,🎮 Gaming
  - DOMAIN-SUFFIX,steampowered.com,🎮 Gaming

  # Line Level 5:Special Apps
  - DOMAIN-SUFFIX,telegram.org,💬 Instant Messaging
  - DOMAIN-SUFFIX,whatsapp.com,💬 Instant Messaging

  # FinalRules
  - GEOIP,CN,DIRECT
  - MATCH,🚀 Auto Select

Fine-Grained IP-Based Routing

IP CIDR Rule

rules:
  # Highest priority:Local Network IP Direct
  - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve
  - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve
  - IP-CIDR,172.16.0.0/12,DIRECT,no-resolve
  - IP-CIDR,127.0.0.0/8,DIRECT,no-resolve

  # China IP Direct
  - IP-CIDR,1.0.1.0/24,DIRECT,no-resolve
  - IP-CIDR,1.1.1.0/24,DIRECT,no-resolve

  # Specific IP ranges via proxy
  - IP-CIDR,8.8.8.0/24,🚀 Auto Select,no-resolve
  - IP-CIDR,1.1.1.0/24,🚀 Auto Select,no-resolve

  # FinalRules
  - MATCH,🚀 Auto Select

GeoIP-Based Geographic Routing

GeoIP Rule

rules:
  # China IP Direct
  - GEOIP,CN,DIRECT

  # US traffic -> US group Node
  - GEOIP,US,🇺🇸 US Node

  # Japan traffic -> Japan group Node
  - GEOIP,JP,🇯🇵 Japan Node

  # EU traffic -> EU nodes
  - GEOIP,DE,🇩🇪 EU nodes
  - GEOIP,FR,🇫🇷 EU nodes
  - GEOIP,GB,🇬🇧 EU nodes

  # Default proxy
  - MATCH,🚀 Auto Select
⚠️
routing rules

Rule, .Rule, Rule.Ruleroutingerror.

Advanced Policy Group Configuration

Policy groups not only combine nodes but also implement complex traffic control and automatic selection logic. Mastering advanced policy group configuration is key to optimizing proxy performance.

Advanced Fallback Usage

article14.advanced-groups.auto.h3_1

proxy-groups:
  # Primary layer: automatic speed test
  - name: "🇭🇰 Hong Kong primary node"
    type: url-test
    proxies:
      - "HK-001"
      - "HK-002"
      - "HK-003"
    url: "http://www.gstatic.com/generate_204"
    interval: 300
    tolerance: 50

  # Failover layer: monitor primary health
  - name: "🚀 Auto Select"
    type: fallback
    proxies:
      - "🇭🇰 Hong Kong primary node"
      - "🇯🇵 Japan backup node"
      - "🇸🇬 Singapore backup node"
      - "DIRECT"
    url: "http://www.gstatic.com/generate_204"
    interval: 300

Load Balance Optimization

article14.advanced-groups.auto.h3_2

proxy-groups:
  # Consistent-hash load balancing:Same connection uses the same node
  - name: "⚖️ consistent hashing"
    type: load-balance
    proxies:
      - "HK-001"
      - "HK-002"
      - "HK-003"
      - "JP-001"
      - "JP-002"
    url: "http://www.gstatic.com/generate_204"
    interval: 300
    strategy: consistent-hashing

  # Round-robin load balancing:Switch nodes in sequence
  - name: "⚖️ round-robin"
    type: load-balance
    proxies:
      - "HK-001"
      - "HK-002"
      - "HK-003"
    url: "http://www.gstatic.com/generate_204"
    interval: 300
    strategy: round-robin

URL Test Parameter Tuning

article14.advanced-groups.auto.h3_3

proxy-groups:
  # chained proxy:Traffic goes through two proxies Nodes
  - name: "🔗 double encryption"
    type: relay
    proxies:
      - "HK-001"
      - "JP-001"

  # Use case: chain proxy in high-risk networks
  - name: "🔐 extra secure"
    type: relay
    proxies:
      - "HK-001"
      - "SG-001"
      - "JP-001"

rules:
  - DOMAIN-SUFFIX,sensitive.com,🔗 double encryption

Relay Chain Proxy

policy groups

proxy-groups:
  # Regional groups
  - name: "🇭🇰 Hong Kong"
    type: url-test
    proxies:
      - "HK-001"
      - "HK-002"
      - "HK-003"
    url: "http://www.gstatic.com/generate_204"
    interval: 300

  - name: "🇯🇵 Japan"
    type: url-test
    proxies:
      - "JP-001"
      - "JP-002"
    url: "http://www.gstatic.com/generate_204"
    interval: 300

  # Destination groups (streaming, gaming, etc.)
  - name: "🎬 Streaming"
    type: select
    proxies:
      - "🇭🇰 Hong Kong"
      - "🇯🇵 Japan"
      - "🇺🇸 US"

  # Global Select group
  - name: "🚀 Global Select"
    type: select
    proxies:
      - "🎬 Streaming"
      - "🇭🇰 Hong Kong"
      - "🇯🇵 Japan"
      - "DIRECT"

Automation & Scripts

Through automation scripts, you can automatically switch configurations, update subscriptions, and execute maintenance tasks, greatly improving usage efficiency.

Automatic Configuration Switching

article14.automation.auto.h3_1

#!/bin/bash

# ClashX config backup and restore script

CLASH_CONFIG_DIR="$HOME/.config/clash"
BACKUP_DIR="$HOME/.clash_backup"
BACKUP_DATE=$(date +%Y%m%d_%H%M%S)

# Create backup
backup_config() {
    mkdir -p "$BACKUP_DIR"
    cp "$CLASH_CONFIG_DIR/config.yaml" "$BACKUP_DIR/config_$BACKUP_DATE.yaml"
    echo "Config backed up to: $BACKUP_DIR/config_$BACKUP_DATE.yaml"
}

# Restore config
restore_config() {
    local latest_backup=$(ls -t "$BACKUP_DIR"/config_*.yaml | head -1)
    if [ -z "$latest_backup" ]; then
        echo "No backup file found"
        return 1
    fi
    cp "$latest_backup" "$CLASH_CONFIG_DIR/config.yaml"
    echo "Config restored"
}

# Reload config
reload_config() {
    curl -X PUT http://127.0.0.1:9090/configs -H "Content-Type: application/json" \
        -d "{\"path\": \"$CLASH_CONFIG_DIR/config.yaml\"}"
    echo "Config reloaded"
}

case "$1" in
    backup) backup_config ;;
    restore) restore_config ;;
    reload) reload_config ;;
    *) echo "Usage: $0 {backup|restore|reload}" ;;
esac

Scheduled Task Automation

Cron

#!/bin/bash

# Scheduled updates ClashX Rule providers

CLASH_HOME="$HOME/.config/clash"
API_URL="http://127.0.0.1:9090"
SECRET="your-secret-key"

# Update rule providers
update_rule_providers() {
    local providers=("reject" "proxy" "direct" "streaming")

    for provider in "${providers[@]}"; do
        echo "Updating rule provider: $provider"
        curl -X PUT "$API_URL/providers/rules/$provider" \
            -H "Authorization: Bearer $SECRET"
        sleep 2
    done

    echo "All rule providers have been updated"
}

# Check ClashX status
check_clash_status() {
    local response=$(curl -s -w "\n%{http_code}" "$API_URL/version")
    local http_code=$(echo "$response" | tail -n 1)

    if [ "$http_code" == "200" ]; then
        echo "ClashX is running normally"
        return 0
    else
        echo "ClashX status is abnormal, attempting restart"
        killall -9 ClashX 2>/dev/null || true
        sleep 2
        open /Applications/ClashX.app
        return 1
    fi
}

# Main function
main() {
    check_clash_status
    if [ $? -eq 0 ]; then
        update_rule_providers
    fi
}

main
                            
💡
Crontab

crontab: crontab -e 2 Rule: 0 2 * * * /path/to/update-rules.sh : 0 * * * * /path/to/check-status.sh

Subscription Update Automation

Python API

#!/usr/bin/env python3

import requests
import json
import yaml
from datetime import datetime

class ClashXManager:
    def __init__(self, api_url="http://127.0.0.1:9090", secret=None):
        self.api_url = api_url
        self.headers = {}
        if secret:
            self.headers["Authorization"] = f"Bearer {secret}"

    def get_proxies(self):
        """Get all proxy nodes"""
        response = requests.get(f"{self.api_url}/proxies", headers=self.headers)
        return response.json() if response.status_code == 200 else None

    def get_traffic_stats(self):
        """Get traffic statistics"""
        response = requests.get(f"{self.api_url}/traffic", headers=self.headers)
        return response.json() if response.status_code == 200 else None

    def test_proxy_speed(self, proxy_name, url="http://www.gstatic.com/generate_204"):
        """Test proxy speed"""
        test_url = f"{self.api_url}/proxies/{proxy_name}/delay?url={url}"
        response = requests.get(test_url, headers=self.headers)
        return response.json() if response.status_code == 200 else None

    def switch_proxy(self, group_name, proxy_name):
        """Switch proxy used by policy group"""
        data = json.dumps({"name": proxy_name})
        response = requests.put(
            f"{self.api_url}/proxies/{group_name}",
            data=data,
            headers={**self.headers, "Content-Type": "application/json"}
        )
        return response.status_code == 204

    def get_logs(self, level="info"):
        """Get logs"""
        response = requests.get(f"{self.api_url}/logs?level={level}", headers=self.headers)
        return response.json() if response.status_code == 200 else None

    def batch_test_proxies(self, proxy_names):
        """Batch Test proxy speed"""
        results = {}
        for proxy in proxy_names:
            result = self.test_proxy_speed(proxy)
            if result:
                results[proxy] = result.get("delay", -1)
        return results

# Usage example
if __name__ == "__main__":
    manager = ClashXManager(secret="your-secret-key")

    # Get proxy info
    proxies = manager.get_proxies()
    if proxies:
        print(json.dumps(proxies, indent=2, ensure_ascii=False))

    # Get traffic statistics
    stats = manager.get_traffic_stats()
    print(f"Upload: {stats['up']} B/s, Download: {stats['down']} B/s")

    # Batch test proxies
    proxy_names = ["HK-001", "JP-001", "US-001"]
    speeds = manager.batch_test_proxies(proxy_names)
    print("Proxy speed test results:")
    for proxy, speed in sorted(speeds.items(), key=lambda x: x[1]):
        print(f"  {proxy}: {speed}ms")

Performance Optimization Tips

Beyond basic configuration, there are many techniques that can further improve ClashX performance and reduce resource usage.

DNS Resolution Optimization

performance DNS configuration

dns:
  enable: true
  listen: 0.0.0.0:53
  enhanced-mode: fake-ip  # Better performance, but slightly lower compatibility

  # Fake-IP address pool configuration
  fake-ip-range: 198.18.0.1/16

  # Domains to exclude when using Fake-IP
  fake-ip-filter:
    - "*.lan"
    - "*.local"
    - "*.internal"
    - localhost.ptlogin2.qq.com
    - "*.qq.com"
    - "*.tencent.com"

  # Primary DNS servers (fast for mainland China lookups)
  nameserver:
    - 119.29.29.29  # DNSPod (CN)
    - 223.5.5.5     # AliDNS (CN)
    - https://doh.pub/dns-query  # DoH is more secure

  # Fallback DNS (used when primary DNS fails)
  fallback:
    - https://1.1.1.1/dns-query    # Cloudflare DoH
    - https://dns.google/dns-query  # Google DoH
    - https://9.9.9.9/dns-query     # Quad9 DoH

  # Domain-specific DNS (key optimization)
  nameserver-policy:
    # Use domestic DNS for domestic domains
    "geosite:cn":
      - 119.29.29.29
      - 223.5.5.5

    # Use global DNS for international domains
    "geosite:geolocation-!cn":
      - https://1.1.1.1/dns-query
      - https://dns.google/dns-query

    # DNS for specific domains
    "domain:example.com":
      - 119.29.29.29

    "domain:google.com":
      - https://8.8.8.8/dns-query

Connection Optimization

article14.performance.auto.h3_2

general:
  # Outbound interface
  interface-name: en0

  # Enable concurrent TCP connections
  tcp-concurrent: true

  # UDP connection timeout (milliseconds)
  udp-timeout: 300

  # Idle connection timeout
  keep-alive-interval: 15

  # SOCKS5 UDP support
  socks-version: 5

# Advanced performance tuning parameters
experimental:
  # Enable interface detection
  interface-name: en0

  # Ignore domains that fail to resolve (reduces retries)
  ignore-resolve-fail: true
                            

Resource Usage Optimization

Ruleperformance

Rule types performance (fast → slow):
1. IP-CIDR/IP6-CIDR (fastest, O(1) lookup)
   Time: ~0.1ms

2. DOMAIN-SUFFIX (fast, trie lookup)
   Time: ~0.2-0.5ms

3. DOMAIN (medium, exact match)
   Time: ~0.3-0.8ms

4. DOMAIN-KEYWORD (slower, substring match)
   Time: ~1-2ms

5. GEOIP (slower, requires IP database lookup)
   Time: ~2-5ms

6. RULE-SET (depends on rule-set size)
   Time: ~0.5-5ms
💡
performance optimization

• IP-CIDR Rule, GEOIP • Rule • RuleRule • Rule providers

Rule Optimization & Maintenance

Well-organized and maintained rules are key to ensuring long-term stability of ClashX. Here are professional rule management techniques.

Rule Providers Usage

Rule

rule-providers:
  # Ad BlockingRules
  reject:
    type: http
    behavior: domain
    url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/reject.txt"
    path: ./ruleset/reject.yaml
    interval: 86400  # Update once every 24 hours

  # Proxy rules
  proxy:
    type: http
    behavior: domain
    url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/proxy.txt"
    path: ./ruleset/proxy.yaml
    interval: 86400

  # DirectRules
  direct:
    type: http
    behavior: domain
    url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/direct.txt"
    path: ./ruleset/direct.yaml
    interval: 86400

  # Streaming rules
  streaming:
    type: http
    behavior: domain
    url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/streaming.txt"
    path: ./ruleset/streaming.yaml
    interval: 86400

  # Apple Rules
  apple:
    type: http
    behavior: domain
    url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/apple.txt"
    path: ./ruleset/apple.yaml
    interval: 86400

  # Google Rules
  google:
    type: http
    behavior: domain
    url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/google.txt"
    path: ./ruleset/google.yaml
    interval: 86400

  # China IP rules
  cncidr:
    type: http
    behavior: ip
    url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/cncidr.txt"
    path: ./ruleset/cncidr.yaml
    interval: 86400

  # Global IP rules
  lancidr:
    type: http
    behavior: ip
    url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/lancidr.txt"
    path: ./ruleset/lancidr.yaml
    interval: 86400

# Use rule providers
rules:
  # Local NetworkDirect
  - RULE-SET,lancidr,DIRECT

  # Ad Blocking
  - RULE-SET,reject,REJECT

  # DirectRules
  - RULE-SET,direct,DIRECT

  # Streaming
  - RULE-SET,streaming,🎬 Streaming

  # Apple
  - RULE-SET,apple,🍎 Apple Services

  # Google
  - RULE-SET,google,🔍 Google Services

  # China IP
  - RULE-SET,cncidr,DIRECT

  # Proxy rules
  - RULE-SET,proxy,🚀 Auto Select

  # FinalRules
  - MATCH,🚀 Auto Select

Rule Maintenance Best Practices

Rule

#!/usr/bin/env python3

import requests
import yaml
from pathlib import Path

class RuleManager:
    """Dynamic rule management tool"""

    def __init__(self, config_path):
        self.config_path = Path(config_path)
        self.config = self._load_config()

    def _load_config(self):
        """Load configuration file"""
        with open(self.config_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)

    def _save_config(self):
        """Save configuration file"""
        with open(self.config_path, 'w', encoding='utf-8') as f:
            yaml.dump(self.config, f, allow_unicode=True, default_flow_style=False)

    def add_rule(self, rule_text, position=None):
        """Add a new rule"""
        if 'rules' not in self.config:
            self.config['rules'] = []

        if position is None:
            # Add near the end (before the MATCH rule)
            position = len(self.config['rules']) - 1

        self.config['rules'].insert(position, rule_text)
        self._save_config()
        print(f"Rule added: {rule_text}")

    def remove_rule(self, keyword):
        """Remove rules by keyword"""
        if 'rules' not in self.config:
            return

        original_count = len(self.config['rules'])
        self.config['rules'] = [
            r for r in self.config['rules']
            if keyword not in r
        ]
        removed_count = original_count - len(self.config['rules'])
        self._save_config()
        print(f"Removed {removed_count} rules")

    def update_rule_provider(self, provider_name, new_url):
        """Update rule provider URL"""
        if 'rule-providers' not in self.config:
            self.config['rule-providers'] = {}

        if provider_name in self.config['rule-providers']:
            self.config['rule-providers'][provider_name]['url'] = new_url
            self._save_config()
            print(f"Rule provider {provider_name} updated")
        else:
            print(f"Rule provider {provider_name} does not exist")

    def list_rules(self, limit=20):
        """List rules"""
        if 'rules' not in self.config:
            return

        rules = self.config['rules'][-limit:]
        for i, rule in enumerate(rules, 1):
            print(f"{i}. {rule}")

# Usage example
manager = RuleManager(Path.home() / '.config/clash/config.yaml')

# Add a new rule
manager.add_rule("DOMAIN-SUFFIX,example.com,DIRECT")

# List rules
manager.list_rules(10)

# Update rule providers
manager.update_rule_provider("proxy", "https://new-url.com/proxy.yaml")
                            

Practical Scenario Configuration

Based on different usage scenarios, here are some complete configuration solutions you can directly reference and use.

Development Environment Configuration

article14.scenarios.auto.h3_1

proxy-groups:
  # Dedicated policy group for streaming
  - name: "🎬 Streaming"
    type: select
    proxies:
      - "🇭🇰 Hong Kong Node"  # Broad catalog
      - "🇯🇵 Japan Node"  # Low latency
      - "🇺🇸 US Node"  # Newest releases
      - DIRECT

  # Dedicated Netflix group
  - name: "🍿 Netflix"
    type: url-test
    proxies:
      - "HK-Netflix-01"
      - "US-Netflix-01"
    url: "https://www.netflix.com/nrdp/v6/www/user"
    interval: 300
    tolerance: 100

rules:
  # Streaming platforms routing
  - DOMAIN-SUFFIX,netflix.com,🍿 Netflix
  - DOMAIN-SUFFIX,nflxso.net,🍿 Netflix
  - DOMAIN-SUFFIX,youtube.com,🎬 Streaming
  - DOMAIN-SUFFIX,youtu.be,🎬 Streaming
  - DOMAIN-SUFFIX,hulu.com,🎬 Streaming
  - DOMAIN-SUFFIX,disneyplus.com,🎬 Streaming
  - DOMAIN-KEYWORD,spotify,🎬 Streaming
                            

Gaming Optimization Configuration

games

proxy-groups:
  # Gaming group: prioritize low latency
  - name: "🎮 Gaming"
    type: url-test
    proxies:
      - "HK-Game-01"
      - "SG-Game-01"
      - "JP-Game-01"
    url: "http://www.gstatic.com/generate_204"
    interval: 300
    tolerance: 30  # Games are latency-sensitive, so keep tolerance low

rules:
  # Steam
  - DOMAIN-SUFFIX,steampowered.com,🎮 Gaming
  - DOMAIN-SUFFIX,steamcommunity.com,🎮 Gaming

  # Epic Games
  - DOMAIN-SUFFIX,epicgames.com,🎮 Gaming
  - DOMAIN-SUFFIX,unrealengine.com,🎮 Gaming

  # other gaming Platforms
  - DOMAIN-SUFFIX,battlenet.com,🎮 Gaming
  - DOMAIN-SUFFIX,playstation.com,🎮 Gaming
                            

Streaming Media Optimization

article14.scenarios.auto.h3_3

proxy-groups:
  # Download-only: prioritize bandwidth
  - name: "📥 Download Acceleration"
    type: load-balance
    proxies:
      - "HK-Download-01"
      - "HK-Download-02"
      - "US-Download-01"
    url: "http://www.gstatic.com/generate_204"
    interval: 300
    strategy: round-robin  # round-round-robin load balancing

rules:
  # Common download sites
  - DOMAIN-SUFFIX,github.com,📥 Download Acceleration
  - DOMAIN-SUFFIX,githubusercontent.com,📥 Download Acceleration
  - DOMAIN-SUFFIX,releases.ubuntu.com,📥 Download Acceleration
                            

Advanced Features Exploration

ClashX has many hidden advanced features that, when properly utilized, can bring unexpected convenience.

External Control API

TUN mode

tun:
  enable: true
  stack: system  # Or gvisor (better performance but slightly lower compatibility)

  # DNS hijacking
  dns-hijack:
    - any:53
    - tcp://any:53

  # Automatic routing
  auto-route: true

  # Automatically detect interface
  auto-detect-interface: true

  # Specify network interface (optional)
  interface-name: en0

  # Optimized MTU size
  mtu: 9000
                            

TUN Mode Advanced Applications

API

#!/usr/bin/env python3

import requests
import json
import asyncio
from datetime import datetime

class ClashXDashboard:
    """Advanced ClashX Dashboard API usage"""

    def __init__(self, base_url="http://127.0.0.1:9090", secret=None):
        self.base_url = base_url
        self.headers = {"Content-Type": "application/json"}
        if secret:
            self.headers["Authorization"] = f"Bearer {secret}"

    def get_system_info(self):
        """Get system information"""
        response = requests.get(f"{self.base_url}/version", headers=self.headers)
        return response.json() if response.status_code == 200 else None

    def get_connections(self):
        """Get current connections"""
        response = requests.get(f"{self.base_url}/connections", headers=self.headers)
        return response.json() if response.status_code == 200 else None

    def get_traffic_stats(self):
        """Get traffic statistics"""
        response = requests.get(f"{self.base_url}/traffic", headers=self.headers)
        if response.status_code == 200:
            data = response.json()
            return {
                "upload": data["up"],
                "download": data["down"],
                "timestamp": datetime.now()
            }
        return None

    def change_mode(self, mode):
        """Switch mode: rule, global, direct"""
        valid_modes = ["rule", "global", "direct"]
        if mode not in valid_modes:
            return False

        data = json.dumps({"mode": mode})
        response = requests.put(
            f"{self.base_url}/configs",
            data=data,
            headers=self.headers
        )
        return response.status_code == 200

    def get_rules_info(self):
        """Get rule information"""
        response = requests.get(f"{self.base_url}/rules", headers=self.headers)
        return response.json() if response.status_code == 200 else None

    def test_url_latency(self, url, timeout=5000):
        """Test URL latency"""
        response = requests.get(
            f"{self.base_url}/configs/latency?url={url}&timeout={timeout}",
            headers=self.headers
        )
        return response.json() if response.status_code == 200 else None

    def get_proxy_latency(self, proxy_name, url="http://www.gstatic.com/generate_204"):
        """Test latency for a single proxy"""
        response = requests.get(
            f"{self.base_url}/proxies/{proxy_name}/delay?url={url}",
            headers=self.headers
        )
        return response.json() if response.status_code == 200 else None

# Usage example: real-time traffic monitoring
async def monitor_traffic():
    dashboard = ClashXDashboard(secret="your-secret")

    print("Starting traffic monitoring...")
    while True:
        stats = dashboard.get_traffic_stats()
        if stats:
            print(f"[{stats['timestamp']}] Upload: {stats['upload']:.2f} B/s, "
                  f"Download: {stats['download']:.2f} B/s")
        await asyncio.sleep(2)

# Run the monitor
# asyncio.run(monitor_traffic())
                            

Custom Rule Sets

article14.advanced-features.auto.h3_3

general:
  # Enable external controller
  external-controller: 0.0.0.0:9090

  # API access secret (strongly recommended)
  secret: "your-very-secure-secret-key-here"

  # CORS support
  external-ui: true

  # External UI URL
  external-ui-url: "https://clash.razord.top/"
                            
⚠️
article14.advanced-features.auto.strong1

• API • ClashX API • ClashX • API

performance

Before DNS optimization
DNS Lookup: 80ms
After DNS optimization
DNS Lookup: 15ms
Before Rule Optimization
Average Latency: 120ms
After Rule Optimization
Average Latency: 45ms

ClashX

  • Rule: Rule > Rule, Rule
  • DNS configuration: Fake-IP performance, nameserver-policy
  • policy groups: ,
  • Rule: RuleRule,
  • performance: CPU memory usage, Rule providers
  • : ,
  • : API , ,

Common Questions and Solutions

Q
Q: Ruleroutingerror?

A: Rule, Rule. DEBUG, Rule.

Q
Q: ?

A: TUN mode, system proxy; DNS , Fake-IP; Rulerouting.

Q
Q: ClashX CPU ?

A: DNS configuration, GeoIP Rule; Rule providers; .