2.18. Inserting Firewall Rules
Problem
Rather than appending a rule to a chain, you want to insert or replace one elsewhere in the chain.
Solution
Instead of the -A option, use -I to insert or -R to replace. You’ll need to know the numeric position, within the existing rules, of the new rule. For instance, to insert a new rule in the fourth position in the chain:
# iptables -Ichain
4...specification...
# ipchains -Ichain
4...specification...
To replace the second rule in a chain:
# iptables -Rchain
2...specification...
# ipchains -Rchain
2...specification...
Discussion
When you insert a rule at position N in a chain, the old rule N becomes rule N+1, rule N+1 becomes rule N+2, and so on. To see the rules in a chain in order, so you can determine the right numeric offset, list the chain with -L. [Recipe 2.16]
See Also
iptables(8), ipchains(8).
Get Linux Security Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.