Configure port forwarding in CentOS
Enable IP Forwarding
First, enable the IP forwarding function, which is disabled by default.
Temporary modification:
# echo 1 >/proc/sys/net/ipv4/ip_forward
The modification takes effect immediately after the modification, but if the system is restarted, It is restored to the default value 0.
Permanent modification:
Vi/etc/sysctl. conf # Find the following value and change 0 to 1net. ipv4.ip _ forward = 1 # sysctl-p (to take effect immediately)
Default Value0
Is to prohibit ip Forwarding, change1
Enable the ip forwarding function.
Configure port forwarding
Assume that the user accesses172.16.4.247:728
I want it to forward172.16.4.97:80
:
# Iptables-t nat-a prerouting-p tcp-d 113.108.110.61 -- dport 728-j DNAT -- to-destination 172.16.4.97: 80 # iptables-t nat-a postrouting-p tcp-s 172.16.4.97 -- sport 80-j SNAT -- to-source 172.16.4.247 # service iptables save (save the current rule to/etc/sysconfig) /iptables)
Alternatively, you can directly modify/etc/sysconfig/iptables
File:
-A PREROUTING -d 172.16.4.247/32 -p tcp -m tcp --dport 728 -j DNAT --to-destination 172.16.4.97:80-A POSTROUTING -s 172.16.4.97/32 -p tcp -m tcp --sport 80 -j SNAT --to-source 172.16.4.247
Finally, do not forget to open port 728.
-A INPUT -p tcp -m state --state NEW -m tcp --dport 728 -j ACCEPT
After the configuration is complete, remember to restart the Firewall:
# service iptables restart
Local port forwarding
If you only need to forward different ports on the local machine, it is easier. For example, to access http: // ip: 729, I want to return http: // ip: 80. The configuration is as follows:
[root@localhost sbin]# iptables -t nat -A PREROUTING -p tcp --dport 729 -j REDIRECT --to-ports 80[root@localhost sbin]# service iptables save[root@localhost sbin]# service iptables restart