Short post to explain how to redirect port in Linux using iptables.
![](https://z5.kerneltalks.com/wp-content/uploads/2020/06/How-to-redirect-port-in-Linux-using-iptables.png)
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 :
- Basics of iptables
- Configuration of iptables policies
- Flushing iptables rules
- 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