Recommended Services
Supported Scripts

Network Address Translation (NAT) allows multiple devices on a private network to share a single public IP address for internet access. This guide configures a Linux server as a NAT gateway using iptables (with a nftables equivalent for modern systems).

Prerequisites

  • The NAT server must have two network interfaces: one public-facing (eth0) and one private (eth1)
  • Clients on the private network set the NAT server’s private IP as their default gateway

Step 1 — Enable IP Forwarding

# Enable permanently (survives reboot)
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl -p

# Verify
sysctl net.ipv4.ip_forward
# Should output: net.ipv4.ip_forward = 1

Step 2 — Add NAT Rules

Using iptables (CentOS 7 / Older Systems)

# Replace eth0 with your public interface name (check with: ip addr)
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT

# Save rules to persist across reboots
service iptables save
# or:
iptables-save > /etc/sysconfig/iptables

Using nftables (AlmaLinux 8/9, Rocky Linux, RHEL 8+)

nft add table nat
nft add chain nat postrouting { type nat hook postrouting priority 100 ; }
nft add rule nat postrouting oifname "eth0" masquerade

# Save nftables rules
nft list ruleset > /etc/nftables.conf
systemctl enable nftables

Step 3 — Configure Client Default Gateway

On each client device on the private network, set the default gateway to the NAT server’s private IP (e.g., 192.168.1.1). On Linux clients:

# Temporary (lost on reboot)
ip route add default via 192.168.1.1

# Permanent (RHEL/CentOS - edit /etc/sysconfig/network-scripts/ifcfg-eth0)
GATEWAY=192.168.1.1

Verify NAT is Working

# From a client behind the NAT, ping the internet
ping -c 4 8.8.8.8

# Check NAT table on the gateway server
iptables -t nat -L -n -v