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

Article 14 cover image

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

Multi-tier Domain Routing Configuration

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 Optimization

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 Geographic Routing Rules

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
โš ๏ธ
Rule Order is Critical

Rules match from top to bottom and stop at the first match. Place more specific rules before more general ones to avoid routing errors caused by overly broad rules matching first.

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

Multi-tier Failover Configuration

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

Smart Load Balancing Configuration

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

Using Relay Chains for Enhanced Security

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

Nesting and Combining 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

Configuration Backup and Restore Script

#!/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 Scheduled Update Script

#!/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 "Update rule providers: $provider" curl -X PUT "$API_URL/providers/rules/$provider" \ -H "Authorization: Bearer $SECRET" sleep 2 done echo "All rule providers 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 running normally" return 0 else echo "ClashX abnormal status, trying 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 Configuration

Edit crontab: crontab -e. Daily 2AM update rule example: 0 2 * * * /path/to/update-rules.sh. Hourly status check: 0 * * * * /path/to/check-status.sh

Subscription Update Automation

Python API Management Script

#!/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 stats"""
        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 stats
    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

High-Performance DNS Configuration

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

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

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

  # Primary DNS servers (fast domestic resolution)
  nameserver:
    - 119.29.29.29  # DNSPod (CN)
    - 223.5.5.5     # AliDNS (CN)
    - https://doh.pub/dns-query  # DoH protocol is more secure

  # Fallback DNS(used when the 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

Connection Parameters Optimization

general: # outbound interface interface-name: en0 # TCP connection pool size tcp-concurrent: true # UDP connection timeout(ms) udp-timeout: 300 # connection idle timeoutTime keep-alive-interval: 15 # SOCKS5 UDP support socks-version: 5 # Advanced performance tuning parameters experimental: # enable interface probing interface-name: en0 # ignore failed DNS resolves (reduce retries) ignore-resolve-fail: true

Resource Usage Optimization

Rule Type Performance Comparison

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

2. DOMAIN-SUFFIX(fast, prefix-treelookup)
   Time: ~0.2-0.5ms

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

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

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

6. RULE-SET(depends on ruleset size)
   Time: ~0.5-5ms
๐Ÿ’ก
Performance Optimization Tips

โ€ข Prioritize IP-CIDR rules over GEOIP rules โ€ข Place frequently matched rules at the top โ€ข Combine similar rules using rule providers โ€ข Regularly update and clean rule sets

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 Providers Configuration

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  # 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

  # Domestic 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

  # International 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 rules 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

  # Domestic IP
  - RULE-SET,cncidr,DIRECT

  # Proxy rules
  - RULE-SET,proxy,๐Ÿš€ Auto Select

  # FinalRules
  - MATCH,๐Ÿš€ Auto Select

Rule Maintenance Best Practices

Rule Management Script

#!/usr/bin/env python3 import requests import yaml from pathlib import Path class RuleManager: """Dynamic rules management tool""" def __init__(self, config_path): self.config_path = Path(config_path) self.config = self._load_config() def _load_config(self): """Load config file""" with open(self.config_path, 'r', encoding='utf-8') as f: return yaml.safe_load(f) def _save_config(self): """Save config 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 new rules""" if 'rules' not in self.config: self.config['rules'] = [] if position is None: # append at end (before MATCH rules) position = len(self.config['rules']) - 1 self.config['rules'].insert(position, rule_text) self._save_config() print(f"Rules 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 providers 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 providers {provider_name} updated") else: print(f"Rule providers {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 new rules 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

Streaming Media Configuration

proxy-groups: # Streamingdedicated policy group - name: "๐ŸŽฌ Streaming" type: select proxies: - "๐Ÿ‡ญ๐Ÿ‡ฐ Hong Kong Node" # rich content - "๐Ÿ‡ฏ๐Ÿ‡ต Japan Node" # low latency - "๐Ÿ‡บ๐Ÿ‡ธ US Node" # latest content - DIRECT # Netflix only - 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

Gaming Optimization Configuration

proxy-groups: # Gaming group๏ผšlow latencypriority - 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 # gaming is latency-sensitive, low tolerance 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

Download Acceleration Configuration

proxy-groups: # download-only๏ผšbandwidth priority - 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 Configuration

tun: enable: true stack: system # or gvisor(better performancebut lower compatibility) # DNS hijacking dns-hijack: - any:53 - tcp://any:53 # auto routing auto-route: true # auto detect interface auto-detect-interface: true # Specify network interface (optional) interface-name: en0 # MTU size optimization mtu: 9000

TUN Mode Advanced Applications

API Advanced Usage Examples

#!/usr/bin/env python3 import requests import json import asyncio from datetime import datetime class ClashXDashboard: """ClashX Dashboard API Advanced 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 info""" 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 stats""" 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 rules info""" 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: Realtime traffic monitor async def monitor_traffic(): dashboard = ClashXDashboard(secret="your-secret") print("Start monitoring traffic...") 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 monitoring # asyncio.run(monitor_traffic())

Custom Rule Sets

External Controller API Configuration

general: # Enable external controller external-controller: 0.0.0.0:9090 # API access key(strongly recommended to set) secret: "your-very-secure-secret-key-here" # CORS support external-ui: true # external UI path external-ui-url: "https://clash.razord.top/"
โš ๏ธ
Security Tips

โ€ข Always set a strong API access key
โ€ข Never expose ClashX API to the public internet
โ€ข Regularly update ClashX and dependencies
โ€ข Use firewall rules to limit API access in production

Common Configuration Performance Comparison

Before DNS optimization
DNS lookup: 80ms
After DNS optimization
DNS lookup: 15ms
Before rule optimization
Avg latency: 120ms
After rule optimization
Avg latency: 45ms

ClashX Advanced Configuration Best Practices

  • Rule Priority: Specific rules > general rules, frequently used rules first
  • DNS Configuration: Use Fake-IP mode for better performance, configure nameserver-policy properly
  • Policy Group Design: Layered design, fast failover for small traffic issues
  • Rule Maintenance: Use rule providers instead of inline rules, update regularly
  • Performance Monitoring: Check CPU and memory usage regularly, optimize rule set size
  • Backup & Restore: Regular config backups, establish rollback mechanism
  • Security Hardening: Set API keys, restrict external access, update regularly

FAQ & Solutions

Q
Q: Rules conflicting causing routing errors?

A: Check rule order, ensure more specific rules come first. Use DEBUG log level to see which rules are actually matched.

Q
Q: Some apps timing out?

A: Try disabling TUN mode and use system proxy instead; check DNS settings, you may need to exclude some domains from Fake-IP; verify routing rules are correct.

Q
Q: ClashX using high CPU?

A: Optimize DNS configuration, disable unnecessary GeoIP rules; reduce rule set size; check for excessive connection logging.