After migrating websites to a new server, you need to point domains to the new server by changing the name server or editing DNS. DNS propagation can take a few hours, during this time visitors to the website still see the website from the OLD server IP. If visitor signup or make a purchase on the OLD server after the migration, this data will be lost. To avoid this, you can use iptables to forward all traffic to the new server IP address.
The following steps need to be done on the OLD server. First, enable IP forwarding
vi /etc/sysctl.conf
Add
net.ipv4.ip_forward=1
Make it active with command
sysctl -p
If you only needed for the current session, you can run the command
echo 1 > /proc/sys/net/ipv4/ip_forward
For forwarding all incoming traffic on Port 80 and 443 to the new server IP, use
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination NEW_SERVER_IP_HERE:80
iptables -t nat -A PREROUTING -p tcp --dport 443 -j DNAT --to-destination NEW_SERVER_IP_HERE:443
iptables -t nat -A POSTROUTING -j MASQUERADE
NEW_SERVER_IP_HERE = replace with IP address of the new server.
Now any traffic coming to the OLD server on ports 80 and 443 will be forwarded to the new server IP address. If you need to forward any port, just duplicate the command and change the port number as required.
If you want to remove the rules, you can flush iptables NAT rules with
iptables -t nat -F
To View iptables NAT rules
iptables -t nat -L
To make the iptables rules permanent on RHEL based Linux, run
iptables-save > /etc/sysconfig/iptables
To restore iptabes
iptables-restore < /etc/sysconfig/iptables
See iptables