iptables insert rule at a specific position (prepend)

This is useful for putting rules on the input chain. Usually, you will have a DROP rule at the end of the chain, so if you want to add a new rule, it should go before DROP.

To start, figure out which line should be used for the new rule.

iptables -L -n --line-numbers

You will see output like this:

Chain INPUT (policy DROP)
num target prot opt source destination
...
22 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:993
23 DROP all -- 0.0.0.0/0 0.0.0.0/0

That means there are 23 rules in the chain.
Next, you should insert the new rule at position 23, like the following:

iptables -I INPUT 23 -p tcp --dport 5222 -j ACCEPT

That will put the new rule at 23 and push the DROP rule down to 24.
Run the first command again and you’ll now see this:

23   ACCEPT  tcp --  0.0.0.0/0     0.0.0.0/0       tcp dpt:5222
24   DROP    all --  0.0.0.0/0     0.0.0.0/0