Tag Archives: iptables port redirection

How to redirect port in Linux using iptables

Short post to explain how to redirect port in Linux using iptables.

Port redirection using iptables

In this short tutorial, we will walk you through the process to redirect port using iptables. How to check port redirection in Linux and how to save iptables rules.

Here are few iptables tutorials for your basics :

  1. Basics of iptables
  2. Configuration of iptables policies
  3. Flushing iptables rules
  4. Disable iptables temporarily

Our requirement is to redirect port 80 to port 8080 in the same server. This can be done by adding rules in PREROUTING chain. So run below command –

[root@kerneltalks ~]# iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

If you have an interface name other than eth0 then you need to edit your command accordingly. You can even add your source and destinations as well in same command using --src and --dst options. Without them, it’s assumed to any source and any destination.

How to check port redirection in iptable

Verify port redirect rule in iptables using below command –

[root@kerneltalks ~]# iptables -t nat -L -n -v
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 REDIRECT   tcp  --  eth0   *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80 redir ports 8080
..............

You can see port 80 is being redirected to port 8080 on the server. Note here target is REDIRECT. Do not get confused with port redirection with port forwarding.

How to save iptables rules

To save iptables rules and make them persistent over reboots use below command –

[root@kerneltalks ~]# iptables-save