How to PREPEND rules rather than APPEND using iptables?

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

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


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


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