25.3.3 Inserting and Replacing Rules in a Chain

Use the iptables -I command to insert a rule in a chain. For example, the following command inserts a rule in the INPUT chain to allow access by TCP on port 80:

# iptables -I INPUT 4 -p tcp -m tcp --dport 80 -j ACCEPT
# iptables -L --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source           destination         
1    ACCEPT     all  --  anywhere         anywhere        state RELATED,ESTABLISHED 
2    ACCEPT     icmp --  anywhere         anywhere            
3    ACCEPT     all  --  anywhere         anywhere            
4    ACCEPT     tcp  --  anywhere         anywhere        tcp dpt:http 
5    ACCEPT     tcp  --  anywhere         anywhere        state NEW tcp dpt:ssh 
6    ACCEPT     udp  --  anywhere         anywhere        state NEW udp dpt:ipp 
7    ACCEPT     udp  --  anywhere         224.0.0.251     state NEW udp dpt:mdns 
8    ACCEPT     tcp  --  anywhere         anywhere        state NEW tcp dpt:ipp 
9    ACCEPT     udp  --  anywhere         anywhere        state NEW udp dpt:ipp 
10   REJECT     all  --  anywhere         anywhere        reject-with icmp-host-prohibited 

Chain FORWARD (policy ACCEPT)
num  target     prot opt source           destination         
1    REJECT     all  --  anywhere         anywhere        reject-with icmp-host-prohibited 

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source           destination

The output from iptables -L shows that the new entry has been inserted as rule 4, and the old rules 4 through 9 are pushed down to positions 5 through 10. The TCP destination port of 80 is represented as http, which corresponds to the following definition in the /etc/services file (the HTTP daemon listens for client requests on port 80):

http            80/tcp          www www-http    # WorldWideWeb HTTP

To replace the rule in a chain, use the iptables -R command. For example, the following command replaces rule 4 in the INPUT chain to allow access by TCP on port 443:

# iptables -I INPUT 4 -p tcp -m tcp --dport 443 -j ACCEPT
# iptables -L --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination         
1    ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED 
2    ACCEPT     icmp --  anywhere             anywhere            
3    ACCEPT     all  --  anywhere             anywhere            
4    ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:https
...

The TCP destination port of 443 is represented as https, which corresponds to the following definition in the /etc/services file for secure HTTP on port 443:

https           443/tcp                         # http protocol over TLS/SSL