ip forward using iptables (port and host redirect)

I have a server that many people are mistaking for my login (ssh) machine, so I decided to forward attempts to ssh into this machine to my real login machine. I found a few posts on this but they were all somewhat incomplete for my purposes There are two problems here, you need to enable ip_forward in the kernel, and then you need to write a nat table for iptables. I'm going to assume you don't have a nat table to begin with.

Step 1, enable ip_forward.

[root@notlogin ~]# sysctl -w net.ipv4.ip_forward=1 net.ipv4.ip_forward = 1 [root@notlogin ~]# echo net.ipv4.ip_forward=1 >>/etc/sysctl.conf
Step 2, create a nat table, you can do this command line (go commando) or edit /etc/sysconfig/iptables, your call.
*nat :PREROUTING ACCEPT [13:1035] :POSTROUTING ACCEPT [5:516] :OUTPUT ACCEPT [12:966] -A PREROUTING -p tcp -m tcp --dport 22 -j DNAT --to-destination -A POSTROUTING -j MASQUERADE COMMIT
If you do this, you won't be able to get into your box via ssh anymore though, you should add an exception for yourself so you can still get into the box via ssh. In the example, the ipaddress of this host is and my client (me) is
*nat :PREROUTING ACCEPT [13:1035] :POSTROUTING ACCEPT [5:516] :OUTPUT ACCEPT [12:966] -A PREROUTING -s -p tcp -m tcp --dport 22 -j DNAT --to-destination -A PREROUTING -p tcp -m tcp --dport 22 -j DNAT --to-destination -A POSTROUTING -j MASQUERADE COMMIT
What we're saying here is that if I'm coming from, just pass me into the real machine (, if I'm not, do the next rule and pass me off to The fun thing is that you can change the port too, so you could have people trying to telnet to port 23 on be redirected to ssh on also.

Hope that saves someone some time.


Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

About the Author...

I published a Thing on @thingiverse! https://t.co/xK6XzN7Cbh #thingalert Fri Jun 12 17:08:46 +0000 2020

Slides from LISA 2019 Linux systems troubleshooting #LISA2019 https://t.co/D4dMKflK6R Tue Oct 29 05:59:30 +0000 2019

https://t.co/AGeihMALAv configuring grub2 with EFI Fri Sep 13 05:20:01 +0000 2019

I published a Thing on @thingiverse! https://t.co/IYpRyEb7Hz #thingalert Tue Jul 23 19:27:57 +0000 2019

Nokogiri install on MacOSX https://t.co/v3An0miW9L Fri Jul 12 15:06:49 +0000 2019