Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How can I remove specific rules from iptables?

I am hosting special HTTP and HTTPS services on the ports 8006 and 8007 respectively. I use iptables to "activate" the server; i.e. to route the incoming HTTP and HTTPS ports

iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 8006 -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 8007 -j ACCEPT
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8006
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8007
iptables -A OUTPUT -t nat -d 127.0.0.1 -p tcp --dport 80 -j REDIRECT --to-ports 8006
iptables -A OUTPUT -t nat -d 127.0.0.1 -p tcp --dport 443 -j REDIRECT --to-ports 8007


However I am having a hard time figuring out the syntax to remove these rules. The only thing that seems to work is a complete flush:

iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT


But that will also delete other iptables rules which are undesired.
by

3 Answers

espadacoder11
Execute the same commands but replace the "-A" with "-D". For example:

iptables -A ...

becomes

iptables -D ...
pankajshivnani123
The best solution that works for me without any problems looks this way:
1. Add temporary rule with some comment:
comment=$(cat /proc/sys/kernel/random/uuid | sed 's/\-//g')
iptables -A ..... -m comment --comment "${comment}" -j REQUIRED_ACTION

2. When the rule added and you wish to remove it (or everything with this comment), do:
iptables-save | grep -v "${comment}" | iptables-restore

So, you'll 100% delete all rules that match the $comment and leave other lines untouched. This solution works for last 2 months with about 100 changes of rules per day - no issues.Hope, it helps
kshitijrana14
First list all iptables rules with this command:
iptables -S


it lists like:
-A XYZ -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT


Then copy the desired line, and just replace -A with -D to delete that:
iptables -D XYZ -p ...

Login / Signup to Answer the Question.