A quick reference for iptables and nftables โ Linux packet filtering. Bookmark this page.
View Rules
# List all rules
sudo iptables -L -n -v
sudo iptables -L -n -v --line-numbers
# List specific chain
sudo iptables -L INPUT -n -v
sudo iptables -L FORWARD -n -v
# List NAT rules
sudo iptables -t nat -L -n -v
# List as commands (for backup)
sudo iptables-saveAdd Rules
# Allow incoming SSH
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow incoming HTTP/HTTPS
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow from specific IP
sudo iptables -A INPUT -s 10.0.0.0/8 -j ACCEPT
# Allow established connections
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow loopback
sudo iptables -A INPUT -i lo -j ACCEPT
# Allow ICMP (ping)
sudo iptables -A INPUT -p icmp -j ACCEPT
# Drop everything else (set as last rule)
sudo iptables -A INPUT -j DROPDelete Rules
# Delete by line number
sudo iptables -L INPUT --line-numbers
sudo iptables -D INPUT 3
# Delete by specification
sudo iptables -D INPUT -p tcp --dport 8080 -j ACCEPT
# Flush all rules
sudo iptables -F
sudo iptables -t nat -F
# Reset to default policy
sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPTNAT and Port Forwarding
# SNAT (source NAT โ masquerade)
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# DNAT (destination NAT โ port forward)
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 10.0.0.5:80
sudo iptables -A FORWARD -p tcp -d 10.0.0.5 --dport 80 -j ACCEPT
# Enable IP forwarding
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forwardSave and Persist
# RHEL/CentOS
sudo iptables-save > /etc/sysconfig/iptables
sudo systemctl enable iptables
# Ubuntu/Debian
sudo apt install iptables-persistent
sudo netfilter-persistent savenftables (Modern Replacement)
# List ruleset
sudo nft list ruleset
# Create table and chain
sudo nft add table inet filter
sudo nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }
# Add rules
sudo nft add rule inet filter input ct state established,related accept
sudo nft add rule inet filter input iif lo accept
sudo nft add rule inet filter input tcp dport {22, 80, 443} accept
sudo nft add rule inet filter input icmp type echo-request accept
# Save
sudo nft list ruleset > /etc/nftables.confTips and Tricks
- Always allow ESTABLISHED,RELATED first for stateful filtering
- Use
iptables-saveto backup before making changes - Test with
-I INPUT 1(insert at top) before committing rules - nftables is the modern replacement โ migrate when possible
- Use
firewall-cmd(firewalld) for a higher-level interface on RHEL