69

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.

Spooler
  • 7,016
  • 16
  • 29
ale
  • 883
  • 2
  • 10
  • 13

4 Answers4

90

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.

Giacomo1968
  • 3,522
  • 25
  • 38
Yanick Girouard
  • 2,295
  • 1
  • 17
  • 18
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.

cjc
  • 24,533
  • 2
  • 49
  • 69
  • 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 03 '13 at 23:21
  • // , Refer to https://fedoraproject.org/wiki/How_to_edit_iptables_rules#Inserting_Rules for more information about how to correctly insert an IPTables rule. – Nathan Basanese Jun 14 '16 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.

Falcon Momot
  • 24,975
  • 13
  • 61
  • 92
AngryWombat
  • 499
  • 3
  • 6
  • 2
    `iptables -L --line-numbers` is a little more platform independant – Sirex Aug 14 '13 at 01: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. – Falcon Momot Aug 14 '13 at 02: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!!!!!

shgnInc
  • 1,634
  • 3
  • 21
  • 29