Home  >  Article  >  System Tutorial  >  How to configure port forwarding under CentOS?

How to configure port forwarding under CentOS?

WBOY
WBOYforward
2024-01-07 14:30:241445browse

Enable IP forwarding

First enable the IP forwarding function, which is turned off by default.

Temporary modification:

# echo 1 >/proc/sys/net/ipv4/ip_forward

It will take effect immediately after modification, but if the system is restarted, it will return to the default value 0.

Permanent modification:

vi /etc/sysctl.conf

# Find the value below and change 0 to 1

net.ipv4.ip_forward = 1

# sysctl –p (make it take effect immediately)

The default value of 0 disables ip forwarding. Changing it to 1 enables the ip forwarding function.

How to configure port forwarding under CentOS?

Configure port forwarding

Assume that when a user accesses 172.16.4.247:728, I want it to be forwarded to 172.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 rules to /etc/sysconfig/iptables)

Alternatively, you can modify the /etc/sysconfig/iptables file directly:

-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 don’t forget to open port 728

-A INPUT -p tcp -m state --state NEW -m tcp --dport 728 -j ACCEPT

After the configuration is completed, remember to restart the firewall:

# service iptables restart

Native port forwarding

If you only need to forward different ports between local machines, it will be easier. For example, when visiting http://ip:729 I want to return the content of 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

The above is the detailed content of How to configure port forwarding under CentOS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete