Stop routing all traffic through OpenVPN and use it on-demand using the tunnel interface name instead
#!/bin/bash
# https://serverfault.com/questions/978701/setting-up-openvpn-as-an-interface-rather-than-routing-all-traffic-from-paid-vpn
# https://serverfault.com/questions/992624/vpn-client-doesnt-have-internet-connection
OVPN_TUN_INTERFACE_NAME="tun0"
# Get the IP address assigned to $OVPN_TUN_INTERFACE_NAME
TUN_IP=$(ip -4 addr show $OVPN_TUN_INTERFACE_NAME | grep -oP '(?<=inet\s)\d+(\.\d+){3}')
# Add the routing table entry if it doesn't exist
if ! grep -q "1000 vpn" /etc/iproute2/rt_tables; then
echo "1000 vpn" >> /etc/iproute2/rt_tables
fi
# Delete any already existing rules that end with 'lookup vpn'
for rule in $(ip rule show | grep 'lookup vpn' | awk '{print $1}' | sed 's/://'); do
ip rule del pref $rule
done
# Delete any already existing routes in the vpn table
ip route flush table vpn
ip route add default via $TUN_IP dev $OVPN_TUN_INTERFACE_NAME table vpn
ip rule add from $TUN_IP/32 lookup vpn
route-nopull
pull-filter ignore redirect-gateway
This is necessary to stop OpenVPN from setting up the routes on its own.
#sndbuf 1024000
#rcvbuf 1024000
txqueuelen 99999
#tun-mtu 1420
comp-lzo no
push "comp-lzo no"
curl --interface tun0 https://icanhazip.com