iptables command snippets

Copy-paste-ready iptables and nft commands for common firewall and NAT tasks.

iptables command snippets

Copy-paste-ready iptables and nft commands for common firewall and NAT tasks.

List All iptables Rules with Line Numbers

iptables displays rules with line numbers for easy deletion:

sudo iptables -L -n -v --line-numbers

Block an IP Address with iptables

iptables drops all traffic from a specific source IP:

sudo iptables -A INPUT -s 203.0.113.45 -j DROP

Allow a Port with iptables

iptables accepts TCP traffic on a specific port:

sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Delete an iptables Rule by Line Number

iptables removes a rule from a chain by its position:

sudo iptables -D INPUT 3

Flush All iptables Rules

iptables removes every rule from every chain:

sudo iptables -F

Save iptables Rules to a File

iptables-save exports the current ruleset:

sudo iptables-save > /etc/iptables/rules.v4

List All nftables Rules

nft displays the complete ruleset:

sudo nft list ruleset

Enable NAT Masquerading with iptables

iptables enables source NAT for outbound traffic:

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE