Static Routes and Policy Routing on Linux

A server with one gateway needs only a default route. As soon as there is a second network, a second uplink, or traffic that must take a different path, you need static routes, and sometimes policy routing: rules that choose the routing table by where a packet comes from or goes to.

Static routes

A route says 'to reach this network, send packets to that gateway'. The gateway must be on a network the host is already attached to. Use replace instead of add in scripts so running them twice is harmless.

ip route replace 10.20.0.0/16 via 192.168.1.254 dev eth0

Tables and rules

Linux keeps several routing tables. Routes go in the main table unless you name another. A rule then decides which table a packet uses, checked in priority order. That is how one subnet leaves through a second uplink while everything else uses the first.

ip route replace default via 203.0.113.1 dev eth0 table 100
ip rule add from 192.168.2.0/24 table 100 priority 1000

Blackholes

A blackhole route drops traffic for a network silently. It is a tidy way to make a private range unreachable, or to stop traffic leaking out through the default route.

ip route replace blackhole 10.99.0.0/16

What can cut you off

Replacing the default route in the main table, blackholing everything, or sending all traffic to another table changes the path your own connection uses. Keep console access when you try them.

Making it permanent

Commands from ip route are gone after a reboot. Put them in netplan (routes and routing-policy), a systemd-networkd drop-in ([Route] and [RoutingPolicyRule]) or post-up lines in ifupdown.

Open the Static routes & policy routing generator

Frequently asked questions

Why does my rule do nothing?

A rule only selects a table. If that table has no route for the destination, the lookup falls through to the next rule. Add a route with the same table number.

What are tables 253, 254 and 255?

default, main and local. They are reserved: use numbers like 100 for your own tables.

Does ip rule add survive a reboot?

No, and running it twice adds the rule twice. Delete it first in scripts, or let netplan or networkd manage it.

Guides