Iptables insert rule at top of tables ( PREPEND rule on Linux )
I want to insert the iptables rule at the top of given tables such as filter table INPUT chain. How do I prepend iptables rules at the top of a filter table on Linux operating system?
iptables is Linux administration tool for IPv4 packet filtering and NAT. One can use iptables/ip6tables to set up, manage, and examine the tables of IPv4 and IPv6 packet filter rules in the Linux kernel. This page shows how to use Iptables to insert rule at top of tables.
Iptables prepend firewall rules to the end of the selected chain
You need to use the following syntax: iptables -I chain [rule-number] firewall-rule For example: sudo iptables -I INPUT 1 -i eth0 -j ACCEPT The above command will insert rule in the INPUT chain as the given rule number. So, if the rule number is 1, the rule or rules are inserted at the head of the chain. This is also the default if no rule number is specified.
Example: Iptables insert rule at top of tables
I am going to INSERT the following rule at of filter table and FORWARD chain: sudo iptables -I FORWARD 1 -m state -s 192.168.2.0/24 -d 192.168.122.0/24 --state NEW,RELATED,ESTABLISHED -j ACCEPT Verify it: sudo iptables -t filter -L FORWARD --line-numbers -n -v
Linux Iptables insert/prepend rule at top of tables command summary
You need to use the following syntax: sudo iptables -I chain [rule-number] firewall-rule To view rules: sudo iptables -t filter -L chain --line-numbers -n -v Where,
-I : Insert rule at given rule number
-t : Specifies the packet matching table such as nat, filter, security, mangle, and raw.
-L : List info for specific chain (such as INPUT/FORWARD/OUTPUT) of given packet matching table
--line-numbers : See firewall rules with line numbers
-n : Do not resolve names using dns i.e. only show numeric output for IP address and port numbers.
-v : Verbose output. This option makes the list command show the interface name, the rule options (if any), and the TOS masks
For more info see iptables man page here or read on your system by typing the following man command: man iptables man ip6tables
The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.