Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Pretty basic question.. How do you PREPEND an iptables rather than APPEND?

I have DROP statements at the bottom of my rules. I have software to add new rules but adding rules after DROP statements isn't good. Every time I want to add a new rule I have to flush the table which is inefficient. Is there a way to prepend a rule i.e. add a rule to the top of the table rather than the bottom?

Many thanks.

share|improve this question

3 Answers 3

up vote 18 down vote accepted

Use the -I switch:

sudo iptables -I INPUT 1 -i lo -j ACCEPT would insert a rule at position #1 in the INPUT chain.

share|improve this answer
Dang! You beat me by 18 seconds... I wasn't quick enough :( –  Yanick Girouard Mar 29 '12 at 19:28
Hehehehehehehe :) –  cjc Mar 29 '12 at 19:30
@YanickGirourad, hah, you got the checkmark! –  cjc Mar 29 '12 at 21:56
Also to note, when using -I INPUT 1, no rule gets overwritten. Instead all rules will be shifted by one position up. –  Abdull Jan 12 '14 at 22:25

To help with determining what line number to add the new rule, I use iptables-save to output the existing rules to the console.

For beginners I can also suggest a cheat card by using webmin administer your rules. It's very friendly and you can easily manually re-order rules in the list. It will also handle the 'slight' variations in redhat vs debian based implementations of iptables.

share|improve this answer
iptables -L --line-numbers is a little more platform independant –  Sirex Aug 14 '13 at 1:32
I'm not sure exactly why one should use webmin for that (or anything). It's far better to learn the command-line way than to use a crutch. –  Falcon Momot Aug 14 '13 at 2:14

-I will insert. You're probably using -A to append.

You can also do iptables -I chain rulenum to insert a rule as number "rulenum" in chain "chain". -R chain rulenum can be used to replace a specific rule at number "rulenum" in chain "chain". iptables -L -n --line-numbers will show the rule numbers in the left-most column.

share|improve this answer
I'm in a rush at the moment or I'd look it up but it would be nice to see an example of how the "chain" works here, or a link. –  PJ Brunet Jul 3 '13 at 23:21

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.