Scenario / Questions

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.

Find below all possible solutions or suggestions for the above questions..

Suggestion: 1

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.

Suggestion: 2

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

Suggestion: 3

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.

Suggestion: 4

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