Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I block all ports except

  1. ssh (port 22)
  2. httpd (port 80)

using iptables and iphains?

share|improve this question

migrated from Jun 15 '10 at 15:17

This question came from our site for professional and enthusiast programmers.

While ochach's answer is technically correct, I think you need to clarify your question. Do you mean "block all input except ssh and http"? If you follow ochach's answer, you won't be able to do anything - no data will be allowed out of your box. – baumgart Jun 15 '10 at 15:37

Ipchains are old and i do not reccomend it

simple script


#start and flush
$IPTABLES -t nat -F

#SSH traffic
$IPTABLES -A INPUT -p tcp --dport 22 -j ACCEPT
#HTTP traffic
$IPTABLES -A INPUT -p tcp --dport 80 -j ACCEPT

iptables -A INPUT -i lo -p all -j ACCEPT
share|improve this answer
I ran this script on my server and locked myself out :) – Zilupe Apr 23 '12 at 22:45
@Zilupe to easily not loose acces to server remember to use cron while editing firewall - like: */2 * * * * iptables -P INPUT ACCEPT – ochach May 28 '12 at 10:04
SSH requires 40 seconds to connect with your rules, against 3 seconds without. I suspect you drop DNS resolution capabilities too. – Dereckson Nov 5 '14 at 3:35
Missing these 2 lines iptables -A INPUT -m conntrack -m cpu -j ACCEPT --ctstate RELATED,ESTABLISHED iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT – cybernard Dec 22 '14 at 18:25

Which Linux distribution? You may be better off using a higher level firewall like ufw:

As root/sudo:

ufw default deny
ufw allow ssh
ufw allow http
ufw enable
share|improve this answer
This is a worthwhile option but consider providing instructions on how to block all incoming traffic except ssh and http, please. – Jeremy W May 30 '12 at 3:48

You must log in to answer this question.