Skip to content

Configure Linux as a router

This page shows the minimal setup for using a Linux box as a router between two network interfaces.

Example topology:

LAN clients <----> eth1 [ Linux router ] eth0 <----> WAN / internet
  • WAN: interface connected to the upstream network or internet
  • LAN: interface connected to the local/private network

Check your interface names:

ip -br link
ip -br addr

Enable IPv4 forwarding

Enable forwarding immediately:

sudo sysctl -w net.ipv4.ip_forward=1

Make it persistent:

echo "net.ipv4.ip_forward = 1" | sudo tee /etc/sysctl.d/99-router.conf
sudo sysctl --system

Check it:

sysctl net.ipv4.ip_forward

Expected:

net.ipv4.ip_forward = 1

Generate iptables router rules

Enter the interface connected to the WAN and the interface connected to the LAN. Choose whether to insert rules at the top of the chains or append them at the end.

Default recommendation: insert at the top. This makes the router rules run before older rules in the same chain.


What the generated rules do

NAT / masquerade

sudo iptables -t nat -I POSTROUTING 1 -o eth0 -j MASQUERADE

This rewrites LAN client source addresses to the router WAN address when traffic leaves through the WAN interface.

Use this when the WAN address is dynamic, such as DHCP or Wi-Fi.

Forward LAN to WAN

sudo iptables -I FORWARD 1 -i eth1 -o eth0 -j ACCEPT

This allows packets from the LAN interface to leave through the WAN interface.

Allow return traffic

sudo iptables -I FORWARD 2 -i eth0 -o eth1 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

This allows replies for connections that LAN clients started.

It does not allow random new incoming traffic from WAN to LAN.


Insert vs append

Mode Command When to use
insert -I CHAIN 1 Put the rule near the top before older rules
append -A CHAIN Put the rule at the end after existing rules

For firewall chains, order matters. The first matching rule usually decides what happens to the packet.


Save rules

Rules added with iptables are usually temporary.

Install persistent rule support on Debian/Ubuntu:

sudo apt install iptables-persistent

Save current IPv4 rules:

sudo iptables-save | sudo tee /etc/iptables/rules.v4

Restore manually:

sudo iptables-restore < /etc/iptables/rules.v4

Remove generated rules

List rules with line numbers:

sudo iptables -t nat -L POSTROUTING -v -n --line-numbers
sudo iptables -L FORWARD -v -n --line-numbers

Delete by line number:

sudo iptables -t nat -D POSTROUTING <line-number>
sudo iptables -D FORWARD <line-number>

Delete carefully. Line numbers change after each delete.

Remote access

Be careful when changing routing and firewall rules over SSH. A wrong interface name, forwarding rule, or default policy can disconnect the machine.