How to configure Linux as a router

· Category: Linux

Short answer

Enable IP forwarding and configure NAT with iptables/nftables to route traffic between networks on Linux.

Steps

  1. Enable IP forwarding:
sudo sysctl -w net.ipv4.ip_forward=1
  1. Make persistent in /etc/sysctl.conf.
  2. Configure NAT:
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
  1. Set up forwarding rules:
sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT

Tips

  • Use nftables or firewalld for modern rule management.
  • Ensure the Linux box has interfaces on both networks.
  • DHCP and DNS services can be added for a complete router solution.

Common issues

  • IP forwarding not persisting after reboot without sysctl config.
  • Firewall rules blocking forwarded traffic.