Configure ufw to redirect http traffic to another IP
I'm trying to redirect all HTTP/HTTPS trafic from one server to another (via IP).
I do use the ufw
firewall. How can I configure it do to so?
Solution 1:
(You will need admin privileges for this, so login as root or use sudo accordingly)
One easy solution is to use iptables
for that:
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -m conntrack --ctstate NEW -j DNAT --to foo_serverip:80
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -m conntrack --ctstate NEW -j DNAT --to foo_serverip:443
iptables -t nat -A PREROUTING -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A POSTROUTING -t nat -j MASQUERADE
will redirect all traffic in the interface eth0
(option: -i) received on port 80 and 443 (option: --dport 80, 443) to a foo_serverip
IP address on port 80 or 443.
After tested you can just save your current iptables rules with
iptables-save > /etc/iptables.rules
and restore them with
iptables-restore < /etc/iptables.rules
Knowing this, the options to restore the rules at boot time are multiple. The most simple one I can think of is to edit your /etc/rc.local
and append the line /sbin/iptables-restore < /etc/iptables.rules
to it.
I do not think ufw
can do any of this just by itself.
Solution 2:
It's possible to configure ufw to make port forward to external IP
-
edit
/etc/default/ufw
to accept forwarding requestsdefault_forward_policy = "accept"
-
edit /etc/ufw/sysctl.conf to allow forwarding
net.ipv4.ip_forward=1
-
edit
/etc/ufw/before.rules
, add the following after the first comment*nat :PREROUTING ACCEPT [0:0] -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination external_ip:80 COMMIT