Linux: 25 Iptables Netfilter Firewall Examples For New SysAdmins

Linux: 25 Iptables Netfilter Firewall Examples For New SysAdmins

Skip to content

Search MENU
Linux: 25 Iptables Netfilter Firewall Examples For New SysAdmins
Posted on December 13, 2011in Categories Iptables, Linux, Linux distribution, Linux Embedded devices, Linux laptop last updated June 15, 2018

Linux comes with a host based firewall called Netfilter. The netfilter is a set of hooks inside the Linux kernel that allows kernel modules to register callback functions with the network stack. A registered callback function is then called back for every packet that traverses the respective hook within the network stack. This Linux based firewall is controlled by the program called iptables to handles filtering for IPv4, and ip6tables handles filtering for IPv6. I strongly recommend that you first read our quick tutorial that explains how to configure a host-based firewall called Netfilter (iptables) under CentOS / RHEL / Fedora / Redhat Enterprise Linux. If you are using Ubuntu/Debian Linux, see how to setup UFW for more info. This post lists most simple iptables solutions required by a new Linux user to secure his or her Linux operating system from intruders.

Linux Iptables Netfilter Firewall Examples For New SysAdmins
This guide shows essential iptables command to control your daily life firewall rules and security of Linux server running on the bare metal server, router, or cloud server.

Linux Iptables Netfilter Firewall Examples For New SysAdmins
Most of the actions listed in this post written with the assumption that they will be executed by the root user running the bash or any other modern shell. Do not type commands on the remote system as it will disconnect your access.
For demonstration purpose, I’ve used RHEL 6.x, but the following command should work with any modern Linux distro that use the netfliter.
It is NOT a tutorial on how to set iptables. See tutorial here. It is a quick cheat sheet to common iptables commands.
1. Displaying the Status of Your Firewall
Type the following command as root:
# iptables -L -n -v

Sample outputs:

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Above output indicates that the firewall is not active. The following sample shows an active firewall:
# iptables -L -n -v

Sample outputs:

Chain INPUT (policy DROP 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 DROP all — * * state INVALID
394 43586 ACCEPT all — * * state RELATED,ESTABLISHED
93 17292 ACCEPT all — br0 *
1 142 ACCEPT all — lo *

Chain FORWARD (policy DROP 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 ACCEPT all — br0 br0
0 0 DROP all — * * state INVALID
0 0 TCPMSS tcp — * * tcp flags:0x06/0x02 TCPMSS clamp to PMTU
0 0 wanin all — vlan2 *
0 0 wanout all — * vlan2
0 0 ACCEPT all — br0 *

Chain OUTPUT (policy ACCEPT 425 packets, 113K bytes)
pkts bytes target prot opt in out source destination

Chain wanin (1 references)
pkts bytes target prot opt in out source destination

Chain wanout (1 references)
pkts bytes target prot opt in out source destination

-L : List rules.
-v : Display detailed information. This option makes the list command show the interface name, the rule options, and the TOS masks. The packet and byte counters are also listed, with the suffix ‘K’, ‘M’ or ‘G’ for 1000, 1,000,000 and 1,000,000,000 multipliers respectively.
-n : Display IP address and port in numeric format. Do not use DNS to resolve names. This will speed up listing.
1.1. To inspect firewall with line numbers, enter:
# iptables -n -L -v –line-numbers

Sample outputs:

Chain INPUT (policy DROP)
num target prot opt source destination
1 DROP all — state INVALID
3 ACCEPT all —
4 ACCEPT all —

Chain FORWARD (policy DROP)
num target prot opt source destination
1 ACCEPT all —
2 DROP all — state INVALID
3 TCPMSS tcp — tcp flags:0x06/0x02 TCPMSS clamp to PMTU
5 wanin all —
6 wanout all —
7 ACCEPT all —

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

Chain wanin (1 references)
num target prot opt source destination

Chain wanout (1 references)
num target prot opt source destination
You can use line numbers to delete or insert new rules into the firewall.

1.2. To display INPUT or OUTPUT chain rules, enter:
# iptables -L INPUT -n -v
# iptables -L OUTPUT -n -v –line-numbers

2. Stop / Start / Restart the Firewall
If you are using CentOS / RHEL / Fedora Linux, enter:
# service iptables stop
# service iptables start
# service iptables restart

You can use the iptables command itself to stop the firewall and delete all rules:
# 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 OUTPUT ACCEPT
# iptables -P FORWARD ACCEPT


-F : Deleting (flushing) all the rules.
-X : Delete chain.
-t table_name : Select table (called nat or mangle) and delete/flush rules.
-P : Set the default policy (such as DROP, REJECT, or ACCEPT).
3. Delete Firewall Rules
To display line number along with other information for existing rules, enter:
# iptables -L INPUT -n –line-numbers
# iptables -L OUTPUT -n –line-numbers
# iptables -L OUTPUT -n –line-numbers | less
# iptables -L OUTPUT -n –line-numbers | grep

You will get the list of IP. Look at the number on the left, then use number to delete it. For example delete line number 4, enter:
# iptables -D INPUT 4

OR find source IP and delete from rule:
# iptables -D INPUT -s -j DROP


-D : Delete one or more rules from the selected chain
4. Insert Firewall Rules
To insert one or more rules in the selected chain as the given rule number use the following syntax. First find out line numbers, enter:
# iptables -L INPUT -n –line-numbers
Sample outputs:

Chain INPUT (policy DROP)
num target prot opt source destination
1 DROP all —
To insert rule between 1 and 2, enter:
# iptables -I INPUT 2 -s -j DROP

To view updated rules, enter:
# iptables -L INPUT -n –line-numbers

Sample outputs:

Chain INPUT (policy DROP)
num target prot opt source destination
1 DROP all —
2 DROP all —
5. Save Firewall Rules
To save firewall rules under CentOS / RHEL / Fedora Linux, enter:
# service iptables save

In this example, drop an IP and save firewall rules:
# iptables -A INPUT -s -j DROP
# service iptables save

For all other distros use the iptables-save command:
# iptables-save > /root/
# cat /root/

6. Restore Firewall Rules
To restore firewall rules form a file called /root/, enter:
# iptables-restore quit
Connection closed.
You can use the nmap command to probe your own server using the following syntax:
$ nmap -sS -p 80

Sample outputs:

Starting Nmap 5.00 ( ) at 2011-12-13 13:19 IST
Interesting ports on (
80/tcp open http

Nmap done: 1 IP address (1 host up) scanned in 1.00 seconds
I also recommend you install and use sniffer such as tcpdupm and ngrep to test your firewall settings.

This post only list basic rules for new Linux users. You can create and build more complex rules. This requires good understanding of TCP/IP, Linux kernel tuning via sysctl.conf, and good knowledge of your own setup. Stay tuned for next topics:

Stateful packet inspection.
Using connection tracking helpers.
Network address translation.
Layer 2 filtering.
Firewall testing tools.
Dealing with VPNs, DNS, Web, Proxy, and other protocols.
Posted by: Vivek Gite
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.


Twitter Facebook Google+
Your support makes a big difference:
I have a small favor to ask. More people are reading the nixCraft. Many of you block advertising which is your right, and advertising revenues are not sufficient to cover my operating costs. So you can see why I need to ask for your help. The nixCraft takes a lot of my time and hard work to produce. If everyone who reads nixCraft, who likes it, helps fund it, my future would be more secure. You can donate as little as $1 to support nixCraft:

Become a Supporter Make a contribution via Paypal/Bitcoin

How to: Linux flush or remove all iptables rules
Ubuntu Linux install and configure OpenSSH (SSHD) server
Linux Iptables: Block All Incoming Traffic But Allow SSH
Iptables MAC Address Filtering
Linux Iptables open Bittorrent tcp ports 6881 to 6889
How do I build a Simple Linux Firewall for…
Linux Iptables: HowTo Block or Open HTTP/Web Service…
Linux Iptables allow or block ICMP ping request
Linux Iptables: How to specify a range of IP…
Linux Iptables block or open DNS / bind service port 53
Linux Iptables Limit the number of incoming tcp…
How to: Linux Iptables block common attacks
Linux Iptables: How to block or open mail server /…
Linux: Iptables Allow MYSQL server incoming request…
How do I use Iptables connection tracking feature?
Join the discussion at
Historical Comment Archive
Comments 81 comment
Happysysadm says: December 13, 2011 at 10:10 am
This is a nice breakdown of IPTABLES indeed! Thank you for taking the time for such a comprehensive explaination… I shall bookmark this!

logicos says: December 13, 2011 at 11:56 am
Try ferm, “for Easy Rule Making” .

In file like “ferm.conf” :

chain INPUT proto tcp dport ssh ACCEPT;

And next:
ferm -i ferm.conf


LeftMeAlone says: December 13, 2011 at 1:58 pm
Can any one tell me the difference between the DROP vs REJECT? Which one is recommended for my mail server?

Worked says: December 13, 2011 at 2:59 pm
LeftMeAlone, “drop” does not send anything to the remote socket while “reject” sending the following message to the remote socket: (icmp destination port unrechable).

Make clean… “drop” maybe the service does not exists. “reject” you can not access to the service.

Joeman1 says: December 13, 2011 at 3:07 pm

DROP will silently drop a packet, not notifying the remote host of any problems, just won’t be available. This way, they will no know if the port is active and prohibited or just not used.

REJECT will send an ICMP packet back to the remote host explaining (For the lack of better words) that the host is administratively denied.

The former is preferred as a remote host will not be able to determine if the port is even up.

The latter is not recommended unless software requires the ICMP message for what ever reason. Its not recommended because the remote host will know that the port is in use, but will not be able to connect to it. This way, they can still try to hack the port and get into the system,

Hope this helps!

Prabal Mishra says: December 13, 2011 at 3:36 pm
thanks !

help for Iptables…………..

smilyface says: December 13, 2011 at 4:11 pm

noone says: December 13, 2011 at 7:28 pm
how about you try
host -t a
a few times, just to see how dns round-rbin works…

noone says: December 13, 2011 at 7:37 pm
also, you can try this


# Clear any previous rules.
/sbin/iptables -F

# Default drop policy.
/sbin/iptables -P INPUT DROP
/sbin/iptables -P OUTPUT ACCEPT

# Allow anything over loopback and vpn.
/sbin/iptables -A INPUT -i lo -s -d -j ACCEPT
/sbin/iptables -A OUTPUT -o lo -s -d -j ACCEPT
/sbin/iptables -A INPUT -i tun0 -j ACCEPT
/sbin/iptables -A OUTPUT -o tun0 -j ACCEPT
/sbin/iptables -A INPUT -p esp -j ACCEPT
/sbin/iptables -A OUTPUT -p esp -j ACCEPT

# Drop any tcp packet that does not start a connection with a syn flag.
/sbin/iptables -A INPUT -p tcp ! –syn -m state –state NEW -j DROP

# Drop any invalid packet that could not be identified.
/sbin/iptables -A INPUT -m state –state INVALID -j DROP

# Drop invalid packets.
/sbin/iptables -A INPUT -p tcp -m tcp –tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP
/sbin/iptables -A INPUT -p tcp -m tcp –tcp-flags SYN,FIN SYN,FIN -j DROP
/sbin/iptables -A INPUT -p tcp -m tcp –tcp-flags SYN,RST SYN,RST -j DROP
/sbin/iptables -A INPUT -p tcp -m tcp –tcp-flags FIN,RST FIN,RST -j DROP
/sbin/iptables -A INPUT -p tcp -m tcp –tcp-flags ACK,FIN FIN -j DROP
/sbin/iptables -A INPUT -p tcp -m tcp –tcp-flags ACK,URG URG -j DROP

# Reject broadcasts to
/sbin/iptables -A INPUT -s -j DROP
/sbin/iptables -A INPUT -d -j DROP
/sbin/iptables -A INPUT -s -j DROP

# Blocked ports
/sbin/iptables -A INPUT -p tcp -m state –state NEW,ESTABLISHED,RELATED –dport 8010 -j DROP

# Allow TCP/UDP connections out. Keep state so conns out are allowed back in.
/sbin/iptables -A INPUT -p tcp -m state –state ESTABLISHED -j ACCEPT
/sbin/iptables -A OUTPUT -p tcp -m state –state NEW,ESTABLISHED -j ACCEPT
/sbin/iptables -A INPUT -p udp -m state –state ESTABLISHED -j ACCEPT
/sbin/iptables -A OUTPUT -p udp -m state –state NEW,ESTABLISHED -j ACCEPT

# Allow only ICMP echo requests (ping) in. Limit rate in. Uncomment if needed.
/sbin/iptables -A INPUT -p icmp -m state –state NEW,ESTABLISHED –icmp-type echo-reply -j ACCEPT
/sbin/iptables -A OUTPUT -p icmp -m state –state NEW,ESTABLISHED –icmp-type echo-request -j ACCEPT

# or block ICMP allow only ping out
/sbin/iptables -A INPUT -p icmp -m state –state NEW -j DROP
/sbin/iptables -A INPUT -p icmp -m state –state ESTABLISHED -j ACCEPT
/sbin/iptables -A OUTPUT -p icmp -m state –state NEW,ESTABLISHED -j ACCEPT

# Allow ssh connections in.
#/sbin/iptables -A INPUT -p tcp -s -m tcp –dport 22 -m state –state NEW,ESTABLISHED,RELATED -m limit –limit 2/m -j ACCEPT

# Drop everything that did not match above or drop and log it.
#/sbin/iptables -A INPUT -j LOG –log-level 4 –log-prefix “IPTABLES_INPUT: ”
/sbin/iptables -A INPUT -j DROP
#/sbin/iptables -A FORWARD -j LOG –log-level 4 –log-prefix “IPTABLES_FORWARD: ”
/sbin/iptables -A FORWARD -j DROP
#/sbin/iptables -A OUTPUT -j LOG –log-level 4 –log-prefix “IPTABLES_OUTPUT: ”
/sbin/iptables -A OUTPUT -j ACCEPT

iptables-save > /dev/null 2>&1
Coolm@x says: December 13, 2011 at 7:38 pm
Nice examples, but missing one. Commonly searched rule is one for masquerade.

Roy says: December 13, 2011 at 10:19 pm
This is extremely useful, somekind of magic and quick recipe…
(Of course now i can’t send mail on my remote server (to strict rate limit …))

3y3lop says: December 14, 2011 at 3:00 am
Nice examples & thanks.

Jani says: December 15, 2011 at 9:00 am
.. I’m anxiously awaiting similar translated to ip6tables. 🙂

Howard says: December 22, 2011 at 3:24 am
A most excellent presentation of iptables setup and use. Really Superior work. Thanks kindly.

Linus Gasser says: December 22, 2011 at 7:32 pm
Point 8:

And for the private address ranges to block on public interfaces, you’ll also want to block

169.254/16 – zeroconf

Pieter says: December 23, 2011 at 5:44 pm
Nice post, thanks! In example #19 there is an error in the last line:

## open access to mysql server for lan users only ##
iptables -I INPUT -p tcp –dport 3306 -j ACCEPT
Should probably be:

## open access to mysql server for lan users only ##
iptables -I INPUT -p tcp -s –dport 3306 -j ACCEPT
shawn cao says: February 24, 2012 at 4:33 am
that is right.

Alejandro says: December 23, 2011 at 11:15 pm
Thanks for this post, I hope you don’t mind if I translate this to spanish and post it on my blog, Mentioning the original source, of course.


strangr says: December 24, 2011 at 12:41 am
Simple rules to share your connection to internet (interface IFNAME) with other hosts on your local LAN (NATTED_SUBNET).
In other words how to do NAT and MASQEURADEing.

# 1) load appropriate kernel module

modprobe iptable_nat
# 2) make sure IPv4 forwarding is enabled

echo 1 > /proc/sys/net/ipv4/ip_forward
# 3) the appropriate rules

iptables -A POSTROUTING -t nat -o $IFNAME -s $NATTED_SUBNET -d 0/0
iptables -A FORWARD -t filter -o $IFNAME -s $NATTED_SUBNET -m state
iptables -A FORWARD -t filter -i $IFNAME -d $NATTED_SUBNET -m state
liRONux says: July 8, 2013 at 12:50 pm
THANKS for this.
How about blocking a website while having those rules?

JD says: December 31, 2011 at 2:27 am
## open access to mysql server for lan users only ##
iptables -I INPUT -p tcp -s –dport 3306 -j ACCEPT

This should be like this:

-s -d -i eth0 -p tcp -m state –state NEW -m tcp –dport 3306 -j ACCEPT

a rule like this should go under RELATED,ESTABLISHED in the INPUT chain

JD says: December 31, 2011 at 2:39 am
For email servers, I have rate limiting rules in place for all service ports.

In the INPUT chain I have the spam firewall ip(s), allowed via port 25.

Then for the email ports, I impose a hit count of 10 in 60 seconds, smart phones, email clients do not poll every second. Anything more than this is dropped and they can continue on a rampage with no affect on the server(s). It took me a while to come up with the rate-limiting chains to work with the email server. Since the Watch Guard XCS devices needed to be exempt from the rules. They have rate-limits on incoming connections as well, a lot better than Barracuda.

I always specify the source/destination interface, state then the port.

MB says: January 3, 2012 at 8:17 am
How do i open the port 25 on a public ip (eg. because it is close, I can only send email but can’t receive email?
But on my localhost it’s open, when I test I able to send and receive only on This is my rule

iptables -A INPUT -p tcp -m tcp –dport 25 -j ACCEPT

when i check netstat -tulpn | grep :25
tcp 0 0* LISTEN 2671/exim4
tcp6 0 0 ::1:25 :::* LISTEN 2671/exim4

Hope you can help me on this matter. I really confused on this one.

Badr Najah says: January 2, 2012 at 6:55 pm
Very useful.

dilip says: January 5, 2012 at 7:36 am
Wooooooooooowwwwww. thats coooool…
very usefull link….

Thanks yar….

nbasileu says: January 9, 2012 at 10:19 am
Rule #14

## *only accept traffic for TCP port # 8080 from mac 00:0F:EA:91:04:07 * ##
# iptables -A INPUT -p tcp –destination-port 22 -m mac –mac-source 00:0F:EA:91:04:07 -j ACCEPT

–destination-port 8080 not 22

Anyway, this is a fu**** good website with fully nice articles.
Very big thx dudes.

Happy new year everyone.

Atul Modi says: March 11, 2012 at 10:16 am
Excellent Stuff Guys!!!

Everyone is putting their part. Great to see this kind of community flourish further.

I am thankful to the ppl who started this website.

Daniel Vieceli says: March 13, 2012 at 2:38 pm
Excellent thanks.

jm says: April 1, 2012 at 3:48 am
Good info and well written.Easy to understand for everyone… I will be back to learn more needed security rules.. Oh and yes I’m a human but I hate to say the definition of human is ( MONSTER) don’t believe me ? Look it up on the net ! Ha ha ha ha
Thank you for this page….

rw1 says: April 5, 2012 at 7:45 am
thank you! for the information on how to delete a firewall rule! priceless! thanks!

Eli says: May 11, 2012 at 12:19 am
How can i use iptable rules to use multiple internet connections for the same bit torrent download?
Actually, i have two broadband connections. I want to combine them. I am told to get load balancing hardware and i cant afford that. So, i did some experimenting. On first DSL modem, i set its IP to be
On second modem, i set its IP to be
Then in windows network adapter settings, i set Metric value of each adapter to 1. Thats about it. My bit torrent downloads/uploads use both my internet connections at the same time which gives effect of combined speed.
Can i do something like that in Linux?
Or, how can i combine two internet connections by using iptables? I dont want any hardware changes. All i have is two DSL modems and two network interface cards. Precise help would be greatly appreciated.

kolya says: May 13, 2012 at 6:55 pm
Hi, got a question to the author of the article. I have tried different kind of commands from the command line, edited the file /etc/sysconfig/iptables directly with following saving and restarting iptables/rebooting system. Nothing helps, my rules get overwritten by the system flushing my new rules or editing them. I tried to open ports (22,21 etc). The goal why I edit my firewall is to get connected to ftp server via FileZilla. Would you recommend me how to open ports? Tell me please if you need any system outputs or something. Cheers

nixCraft says: May 13, 2012 at 8:35 pm
> my rules get overwritten by the system flushing my new rules or editing them

I think you got some sort of script or other firewall product running that is overwriting your rules. Check your cron job and you find the source for the same. If you need further assistance head over to the nixcraft Linux Support forum.

kolya says: May 14, 2012 at 12:21 pm
thanks for your respond, as I am not a specialist I didn’t any changes to my crontab yet, anyway I checked it, also /cron.d and everything connected to cron in /var/spool/…. Nothing about iptables or something. What I noticed there are several iptables files in /etc/sysconfig/: iptables.old written by system-config-firewall, iptables generated by iptables-save with some changes what I didn’t entered.
Here is what I entered from

# iptables -P INPUT ACCEPT
# iptables -F
# iptables -A INPUT -i lo -j ACCEPT
# iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT
# iptables -A INPUT -p tcp –dport 22 -j ACCEPT
# iptables -P INPUT DROP
# iptables -P FORWARD DROP
# iptables -P OUTPUT ACCEPT
# iptables -L -v

Here is what I got in the iptables’s file:

:INPUT DROP [1:40]
:OUTPUT ACCEPT [526:43673]
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp –dport 22 -j ACCEPT
Don’t know why it changes, probably it is aplying kind of default settings, but analyzing this settings the port 22 should be open. Nmap says it is closed, telnet outputs connection refused. Was trying to set samba server with the same result due to my firewall. What to do?

Sigma says: May 25, 2012 at 6:53 am
Thanks a lot for this article, which is extremely easy to understand and follow for beginners as me!

dima says: June 9, 2012 at 10:38 am
Regarding the block #7.1: Only Block Incoming Traffic
The rule
# iptables -A INPUT -m state –state NEW,ESTABLISHED -j ACCEPT
looks dubious to me
Why would you want to allow NEW connections?
In my view it should read
# iptables -A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT

qubits4all says: February 2, 2013 at 8:08 am
I noticed this as well. The rule as given is not right. I’ve been using iptables for a couple of years now, and the INPUT rule here should read:
iptables -A INPUT -m state –state ESTABLISHED,RELATED
(actually the above order is equivalent), because one clearly wouldn’t want to match the NEW state here. Doing so would open up the door to TCP connects (i.e., TCP SYN packets) to any listening TCP services, as well as to UDP datagrams.

Cheers to the author(s) of nixCraft for a nice article & a useful collection of iptables rules. This has become one of my favorite Linux/Unix blogs, so please keep the articles coming.

BiBi says: June 21, 2012 at 3:24 am
Thank you very much, this site is very useful. I love all of you.

Juan says: July 14, 2012 at 1:53 pm
Excellent tutorial. My desire is to block social networking in my job, I did it with squid in transparent mode but skipped to enter https. I did the tests on a virtual pc and it worked fine. The issue is that I is working on the production server. This has two network cards, eth0 traffic where it enters the Internet and eth1 to connect to the network. For the case of Facebook do the following:

# We block Facebook
iptables-A OUTPUT-p tcp-d 443-j DROP
iptables-A OUTPUT-p tcp-d 443-j DROP
iptables-A OUTPUT-p tcp-d 443-j DROP
iptables-A OUTPUT-p tcp-d 443-j DROP
iptables-A OUTPUT-p tcp-d 443-j DROP

Any suggestions?.


jaydatt says: August 30, 2012 at 10:47 am
really helpful article

Borislav Bozhanov says: September 11, 2012 at 11:13 pm

Here is how to BLOCK FACEBOOK with single line command and iptables:

for i in $(nslookup|grep Address|grep -v “#53″|awk ‘{print $2}’); do iptables -I FORWARD -m tcp -p tcp -d $i/24 –dport 443 -j DROP; done

You can replace the website with any other secure (https) you want.

For http websites (non-secure) – use the following line, replacing with the desired domain name:
for i in $(nslookup|grep Address|grep -v “#53″|awk ‘{print $2}’); do iptables -I FORWARD -m tcp -p tcp -d $i/24 –dport 80 -j DROP; done

Don’t forget to save your iptables configuration.

Borislav Bozhanov

Łukasz Bodziony says: September 13, 2012 at 7:37 pm
Thank you!!!

Gus says: September 29, 2012 at 6:51 pm
I’m working with virtual machines. and would like to make a firewall and rootin bash.

My question is this
I have several public ip — IP1 = ( IP2 (=200.xx), IP3 = ·

The issue is that one of them use to Wan IP1.

Now I want to direct traffic from outside to inside. But I also want to redirect the traffic that comes to public ip 2 ( IP2 to the local machine in lan ( and what comes to public ip 3 (IP3) to the local machine (

I can not find examples of how to redirect traffic coming to a specific public IP to a particular LAN private IP.
If you can ask to help me.


## Pello Xabier Altadill Izura

echo -n Aplicando Reglas de Firewall…

## Paramos el ipchains y quitamos el modulo
/etc/rc.d/init.d/firewall stop
rmmod ipchains

## Instalando modulos
modprobe ip_tables
modprobe ip_nat_ftp
modprobe ip_conntrack_ftp

## Variables

## En este caso,
## la tarjeta eth1 es la que va al ROUTER y la eth0 la de la LAN

## Primeras reglas
/sbin/iptables -P INPUT DROP
/sbin/iptables -F INPUT
/sbin/iptables -P OUTPUT ACCEPT
/sbin/iptables -F OUTPUT
/sbin/iptables -P FORWARD ACCEPT
/sbin/iptables -F FORWARD
/sbin/iptables -t nat -F

### En principio, si las reglas INPUT por defecto hacen DROP, no haria falta
### meter mas reglas, pero si temporalmente se pasa a ACCEPT no esta de mas.

## Todo lo que viene de cierta IP se deja pasar (administradores remotos…)
/sbin/iptables -A INPUT -i $EXTIF -s -d -j ACCEPT

## El localhost se deja
/sbin/iptables -A INPUT -i lo -j ACCEPT
/sbin/iptables -A OUTPUT -o lo -j ACCEPT

## Aceptar al exterior al 80 y al 443

# Permitir salida al 80
/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 80 -j ACCEPT
/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –dport 80 -j ACCEPT
# Permitir salida al 443
/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 443 -j ACCEPT
/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –dport 443 -j ACCEPT

## SALIDA SMTP – Para que el servidor se pueda conectar a otros MTA
# Permitir salida SMTP
/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 25 -j ACCEPT
/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –dport 25 -j ACCEPT

## SALIDA FTP – Para que el servidor se pueda conectar a FTPs
/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 21 -m state –state ESTABLISHED -j ACCEPT
/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –dport 21 -m state –state NEW,ESTABLISHED -j ACCEPT
# ftp activo
/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 20 -m state –state ESTABLISHED,RELATED -j ACCEPT
/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –dport 20 -m state –state ESTABLISHED -j ACCEPT
# ftp pasivo
/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 1024:65535 –dport 1024:65535 -m state –state ESTABLISHED -j ACCEPT
/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –sport 1024:65535 –dport 1024:65535 -m state –state ESTABLISHED,RELATED -j ACCEPT
Rogier says: October 23, 2012 at 5:48 am
Hi, I have two interfaces: eth0 (for internal network) and eth1 (WAN). The server does the routing to the clients with the following IPtables:

# Generated by iptables-save v1.4.12 on Fri Oct 19 21:14:26 2012
# Completed on Fri Oct 19 21:14:26 2012
# Generated by iptables-save v1.4.12 on Fri Oct 19 21:14:26 2012
:INPUT ACCEPT [505:53082]
:OUTPUT ACCEPT [247:29622]
-A FORWARD -s -i eth0 -o eth1 -m conntrack –ctstate NEW -j ACCEPT
# Completed on Fri Oct 19 21:14:26 2012
This works fine, however I have no other rules set up. Can anyone help me in deciding what rules I need? the server (who does the NAT) is also running a webserver on port 80, SSH server on 22. All other ports can may be blocked.. how can I achieve this?

Jorge Robles says: October 24, 2012 at 2:37 pm
I use fwbuilder to create my rules, this interface “looks like” checkpoint’s fw1 client to edit rules. Very graphical, and good to work with.

sahil says: November 8, 2012 at 10:14 am
very nice and informative article
it really helped to work for my VPS server

bussy says: November 9, 2012 at 8:09 pm
how i do give access ip ex only for facebook .

Sayajin says: December 19, 2012 at 7:27 am
fb_address=$(dig +tcp +short);
iptables -A OUTPUT -p tcp -s ! -d $fb_address -j DROP;

bahathir says: November 25, 2012 at 3:17 am
For tip #2, it is advisable to run the -P chain ACCEPt first, before flushing it.
# iptables -P INPUT ACCEPT
# iptables -P OUTPUT ACCEPT
# iptables -P FORWARD ACCEPT
# iptables -F
# iptables -t nat -F
# iptables -X
#iptables -t nat -X

Why? If the current chain’s policy is DROP, and you are remotely accessing to the server via SSH, and the rule “-A INPUT -p tcp –dport 22 -j ACCEPT” is still opens the “-P INPUT DROP”. you may disconnected as soon as you flush *-F* the rules, and the default policy “-P INPUT DROP” kicks in. 🙂 If you are working on the local console, it is fine.

Thank you.

qubits4all says: February 2, 2013 at 8:34 am
This is a valid point. Another way to avoid locking oneself out, which I have found very useful for testing firewall changes over an SSH session, is the iptables-apply command (incl. with the Ubuntu iptables package for e.g.). It functions essentially the same as the iptables command, but when applying a rule change it prompts w/ a timeout for a confirmation after making the change. If no response is received (in 30 secs. by default), then it rolls back the change (i.e., add, modify, delete or otherwise).

Once rules have been tested, I save them with iptables-save, and load the stable configuration with an init.d script at system startup (and including support for a ‘restart’ command here, for a clean flush, delete & reapply rules cycle).

levi says: November 27, 2012 at 4:24 am
Could it be you are using iptables save after directly editing? This will overwrite your work. Do a restart to load your newly edited table.

KeepEnEmUp says: December 8, 2012 at 2:32 am
Great Thx for awesome site and for awesome reading,tutos.
Respect And KeepUp dude!

rashid Iqbal says: December 13, 2012 at 11:43 am
from graphical user and groups If I add or delete any user I can’t see any reference log nor in messages or in /var/log/secure file,

Kindly please advise on this that from GUI if we run/execute any command where does the log message will go.

Gangadhar says: February 27, 2013 at 2:50 pm
thank you very much for such a wonderful explanation….. very clear and had nice experience with iptables…

haidt says: March 10, 2013 at 9:04 am
Hi there,

i have a problem, i have got a server and LAN network, and this’s feature

internet (eth0) server (eth1) clients ->
now, i can config to iptables accept all client connect internet, but in this situation, i want to allow only one client (assume:, i try but not completed. pls help me 🙂


Manish Narnaware says: April 24, 2013 at 5:33 am
Thanks a lot.

Orange says: April 25, 2013 at 11:08 pm
Thank you very much. Coincidentally, I just discovered an hour ago that I need to use iptables to allow a tablet computer to talk through my laptop, using the same internet connection. And then I discovered that I can’t remember any of it. I was using IP tables and IP nat 15 years ago, back when it was Darrin Reed’s project (name???), but that was too long ago for my memory. This article will get me back on track fast.
Thanks again.

Le Vu says: May 29, 2013 at 8:23 am
Module xt_connlimit was disabled. How to limit number of connection per IP, can you module limit and recent. Please help me. 🙂

abedatwa says: June 13, 2013 at 7:08 am
thank you

abedatwa says: June 13, 2013 at 7:09 am
thank you for you ivitation

Mark says: August 1, 2013 at 1:33 pm
Thank you for this example. I don’t remember the command line off the top of my head and this gives me enough information to do what I need to do without having to read 30 man pages. If only proper support ( would be so efficient.

paul says: August 3, 2013 at 1:29 am
Enjoyed and appreciated the article and the comments particularly from noone (13 December 2011). I’ve added some of the suggestions to my firewalls.

The first lines in every INPUT are always


123 & 124 represent my external IPs including home and office backup connections.

These entries ensure that whatever errors I make in IPTables I can never lock myself out of my remote servers.

Best regards to all,


John says: August 21, 2013 at 2:40 am
In 7.1, the example provided does not block all incoming traffic like it claims. If you don’t add more parameters, the rule will apply to both directions.

The example rule:

iptables -I INPUT -m state –state NEW,ESTABLISHED -j ACCEPT

This would not only allow for NEW outgoing requests but also NEW incoming requests. The DROP policy for the INPUT chain can’t do it’s job to block incoming connections since it is applied after the rule which allows both NEW incoming and outgoing connections.

sophea says: October 30, 2013 at 8:53 am
I have problem when i add by manually (ex: #iptables -A INPUT -s -p tcp –dport 53 -j ACCEP) but when i restart iptables by service iptables restart it not work because :

1- when i view in /etc/sysconfig/iptables the IP address will be but my land /24
2- problem when i start or stop by system-config-firewall

Can u help me pls?

Mohammad says: February 27, 2014 at 3:38 pm
Hi, I have a question. Could we log packets which are dropped because of forwarding queue is filled (e.g in congestion time)? How do I perform this work?
Regards Mohammad.

juan-vargas says: May 26, 2014 at 12:49 am
Hi there. Greetings from Mexico. Nice examples. Very usefull all of them. But, can I bypass traffic in the port-80 once my iptables-policies are: -P INPUT DROP, -P OUTPUT DROP, -P FORWARD DROP?

thank you all in advance.

Anumod says: August 4, 2014 at 12:47 pm
How to disable sending back TCP Reset to clients or how to increase TCP reset timeout in iptable.
(I am using a raw socket as server and able to receive tcp client SYN request, but before sending SYNACK, tcp reset packet is going from server)

John says: August 9, 2014 at 1:20 am
Hi Guys,

New to IP Tables, need a little advice – I have a guest wifi network setup, how do I block port 25 outgoing for an ip range?

Thanks, John Tankard

Darko Vrsic says: October 15, 2014 at 9:30 am
Very nice!

Thank you!

Bas says: October 15, 2014 at 5:52 pm
Nice breakdown on iptables!

However, I prefer (& recommend) to use a firewall manager (command-line / config file based tool) like shorewall:

Ron Barak says: December 1, 2014 at 4:43 pm
Useful page.
Here’XXX errXXX I found
#18: Established Connections and >>>Restaring<<>>Restaring<<>>Restaring<<< The Linux Firewall

Chống Trộm Quảng Ngãi says: April 30, 2016 at 3:36 am
CSF firewall base on iptables is very good for me. I think new SysAdmins should using CSF firewall.

DECPNQ says: August 23, 2016 at 3:41 pm
Wow. Awesome examples. I loved it. Thanks!!!!!!!!!!!

Paran says: January 5, 2017 at 5:27 pm
Thanks to all, really this site is excellent to gather knowledge.
Right now my boss has assigned me a new task. I would like to share this also need to solve the problem. Please help me.
How to blocked an IP address which is request in my server port (Tomcat) more or equal twenty times per second.
Suppose my server ip is with it’s port is 80. However, another IP address is concurrently requested in my server. IP address may be different. But, it can be identified by their nature. Per second can attack in my server more that 20 times.

ben says: January 29, 2017 at 9:30 pm
can someone put all the recommend lines in one file?
i see the comments here , and i didn’t get it what to put

Mandar says: June 9, 2017 at 7:36 am
Hii All,
Can any one help me for security.
I want to accept traffic over UDP from particular MAC or device

Have a question? Post it on our forum!

Post navigation
Previous post:
Previous post:Download CentOS 6.1 CD / DVD ISO
Next post:
Next post:Linux / UNIX Desktop Fun: Let it Snow On Your Desktop
Tagged as: Tags /etc/sysconfig/iptables, /var/log/messages, Centos iptables rules examples, Debian iptables rules examples, enterprise linux, Fedora iptables rules examples, firewall iptables, iptables command, iptables rules example, iptables rules examples, kernel modules, linux distro, linux kernel, netfilter, RHEL iptables rules examples, Slackware iptables rules examples, Ubuntu iptables rules examples
nixCraft @2000-2018 nixCraft. All rights reserved.
Hosted by Linode
DNS & CDN by Cloudflare
Designed and Developed by Prospect One Prospect One

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.