Skip to content

Instantly share code, notes, and snippets.

@nykma
Last active April 8, 2024 11:36
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nykma/5cdb70dcb7b8c308c12d5b8c5e3d2dfe to your computer and use it in GitHub Desktop.
Save nykma/5cdb70dcb7b8c308c12d5b8c5e3d2dfe to your computer and use it in GitHub Desktop.
Clash linux iptables local redir config

Let Clash handle all local network traffic.

Setup

# Create a separate user to run Clash
useradd clash
# Note down UID
id clash
# Use rest of the file in this gist as usual.

Misc

Docker

Add these into your ~/.docker/config.json

{
  "proxies": {
    "default": {
      "http_proxy": "http://YOUR_NON_127_ADDRESS_OF_CLASH:CLASH_MIXED_PORT",
      "https_proxy": "http://YOUR_NON_127_ADDRESS_OF_CLASH:CLASH_MIXED_PORT",
      "no_proxy": "*.test.example.com,.example2.com,127.0.0.0/8"
    }
  }
}

Should set allow lan to true in your clash config

See also

# /usr/lib/systemd/system/clash.service
[Unit]
Description=A rule based proxy in Go
After=network.target
[Service]
Type=exec
# Important: use the user just created to filter package in iptables
User=clash
Restart=on-failure
# If you want to bind <1024 port:
# AmbientCapabilities=CAP_NET_BIND_SERVICE
ExecStart=/usr/bin/clash -d /etc/clash
[Install]
WantedBy=multi-user.target
#!/bin/bash
# Remove clash redir records
iptables -t nat -D OUTPUT -p tcp -j CLASH
iptables -t nat -F CLASH
iptables -t nat -X CLASH
#!/bin/bash
# Set iptables for clash redir mode
# See also: https://github.com/Dreamacro/clash/issues/158
iptables -t nat -N CLASH
# Avoid package loop
# Use UID of user `clash'
iptables -t nat -A CLASH -m owner --uid-owner 1009 -j RETURN
# Local
iptables -t nat -A CLASH -d 0.0.0.0/8 -j RETURN
iptables -t nat -A CLASH -d 127.0.0.0/8 -j RETURN
iptables -t nat -A CLASH -d 10.0.0.0/8 -j RETURN
iptables -t nat -A CLASH -d 169.254.0.0/16 -j RETURN
iptables -t nat -A CLASH -d 172.16.0.0/12 -j RETURN
iptables -t nat -A CLASH -d 192.168.0.0/16 -j RETURN
iptables -t nat -A CLASH -d 224.0.0.0/4 -j RETURN
iptables -t nat -A CLASH -d 240.0.0.0/4 -j RETURN
# Set redirect port according to your own clash config
iptables -t nat -A CLASH -p tcp -j REDIRECT --to-ports 7892
iptables -t nat -A OUTPUT -p tcp -j CLASH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment