首先把转发策略打开
[root@localhost~]# vi /etc/sysctl.conf net.ipv4.ip_forward=1 [root@localhost~]# sysctl -p
一、把访问192.168.1.125的80端口的请求转发到172.16.119.120的8000端口
[root@localhost ~]# iptables -t nat -A PREROUTING -d 192.168.1.125 -p tcp --dport 80 -j DNAT --to-destination 172.16.119.120:8000
查看路由前nat表
[root@localhost ~]# iptables -t nat -vnL PREROUTING --line-number Chain PREROUTING (policy ACCEPT 2885K packets, 134M bytes) num pkts bytes target prot opt in out source destination 1 29957 1693K DNAT tcp -- * * 0.0.0.0/0 192.168.1.125 tcp dpt:80 to:172.16.119.120:8000
删除路由前第一条规则,注意删除后规则标签会变化,后面的标签会向前移一位
[root@localhost ~]#iptables -t nat -D PREROUTING 1
清空路由前nat表
[root@localhost ~]# iptables -t nat -F PREROUTING [root@localhost ~]# iptables -t nat -vnL PREROUTING --line-number Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes) num pkts bytes target prot opt in out source destination
二、把向172.16.119.120的8000端口请求的数据返回192.168.1.125
[root@localhost ~]# iptables -t nat -A POSTROUTING -d 172.16.119.120 -p tcp --dport 8000 -j SNAT --to-source 192.168.1.125
查看路由后nat表
[root@localhost ~]# iptables -t nat -vnL POSTROUTING --line-number
删除路由后第二条规则,注意删除后规则标签会变化
[root@localhost ~]# iptables -t nat -D POSTROUTING 2
清空路由后nat表
[root@localhost ~]# iptables -t nat -F POSTROUTING [root@localhost ~]# iptables -t nat -vnL POSTROUTING --line-number Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes) num pkts bytes target prot opt in out source destination
清空所有nat表
[root@localhost ~]# iptables -t nat -F
特别注意:以上所有命令执行后的结果都是保存在内存中,重启系统后重置。要执行:
[root@localhost ~]# /sbin/iptables-save
命令保存到磁盘中。不同系统命令略有区别,这里是RHEL7或Centos7