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:
WAN: interface connected to the upstream network or internetLAN: interface connected to the local/private network
Check your interface names:
Enable IPv4 forwarding
Enable forwarding immediately:
Make it persistent:
Check it:
Expected:
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
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
This allows packets from the LAN interface to leave through the WAN interface.
Allow return traffic
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:
Save current IPv4 rules:
Restore manually:
Remove generated rules
List rules with line numbers:
Delete by 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.