68

Pretty basic question: how to PREPEND rules on IPTABLES rather than to APPEND?

I have DROP statements at the bottom of my rules. I have a 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.

4 Answers 4

89

Use the -I switch:

sudo iptables -I INPUT 1 -i lo -j ACCEPT

This would insert a rule at position #1 in the INPUT chain.

6
  • 2
    Dang! You beat me by 18 seconds... I wasn't quick enough :( Mar 29, 2012 at 19:28
  • 1
    Hehehehehehehe :)
    – cjc
    Mar 29, 2012 at 19:30
  • 2
    @YanickGirourad, hah, you got the checkmark!
    – cjc
    Mar 29, 2012 at 21:56
  • 6
    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, 2014 at 22:25
  • 1
    Important note from Abdull.
    – Halsafar
    Feb 4, 2016 at 22:19
20

-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.

2
  • 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, 2013 at 23:21
  • // , Refer to fedoraproject.org/wiki/… for more information about how to correctly insert an IPTables rule. Jun 14, 2016 at 23:26
2

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.

2
  • 2
    iptables -L --line-numbers is a little more platform independant
    – Sirex
    Aug 14, 2013 at 1:32
  • 1
    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. Aug 14, 2013 at 2:14
2

There is a program named iptables-persistent which make iptable's rules persistent as a OS service. this service include a configuration file as the iptables-save export.

So you can reorder the lines in the configuration file and restart the service.

sudo service iptables-persistent restart

So easy!!!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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