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.
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
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
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
โข 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/"
โข 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
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
A: Check rule order, ensure more specific rules come first. Use DEBUG log level to see which rules are actually matched.
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.
A: Optimize DNS configuration, disable unnecessary GeoIP rules; reduce rule set size; check for excessive connection logging.