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
This works like a charm. However I would like to create another script that disables my server again; i.e. restore iptables to the state it was in before running the lines above. 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 is undesired.
Use
-D
command, this is howman
page explains it:Do realize this command, like all other command(
-A
,-I
) works on certain table. If you'are not working on the default table(filter
table), use-t TABLENAME
to specify that target table.Delete a rule to match
Note: This only deletes the first rule matched. If you have many rules matched(this can happen in iptables), run this several times.
Delete a rule specified as a number
Other than counting the number you can list the line-number with
--line-number
parameter, for example:Execute the same commands but replace the "-A" with "-D". For example:
becomes
The best solution that works for me without any problems looks this way:
1. Add temporary rule with some comment:
2. When the rule added and you wish to remove it (or everything with this comment), do:
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
First list all iptables rules with this command:
it lists like:
Then copy the desired line, and just replace
-A
with-D
to delete that:You may also use the rule's number (--line-numbers):
Example output :
So if you would like to delete second rule :
Update
If you use(d) a specific table (eg nat), you have to add it to the delete command (thx to @ThorSummoner for the comment)
Assume that, if you want to remove NAT rules,
List the appended IPtables using the command below,
If you would like to remove the nat rule from the IPtables, just execute the command,
Then, you can verify that,