7

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?

0

2 Answers 2

10

(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.

3
  • if I enter this as sudo, should it work? I guess it would be lost at restart, do you know where I should put this regarding ufw?
    – Olivier
    Jul 26, 2012 at 22:46
  • @Olivier edited, let me know if you have any further doubts. Jul 26, 2012 at 22:58
  • This worked, but I had to disable ufw. Thanks.
    – Tom Aranda
    May 14, 2018 at 23:06
6

It's possible to configure ufw to make port forward to external IP

  1. edit /etc/default/ufw to accept forwarding requests

    default_forward_policy = "accept"

  2. edit /etc/ufw/sysctl.conf to allow forwarding

    net.ipv4.ip_forward=1

  3. 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  
    
4
  • Hmm...what do you mean by ff? I am not seeing that in the /etc/ufw/before.rules file.
    – Tom Aranda
    May 14, 2018 at 23:05
  • It looks like my answer was changed. I don't know what is ff here May 22, 2018 at 20:27
  • Seems this no longer works in 2023. Adding default_forward_policy = "accept" to /etc/default/ufw crashes my ufw service on restart. Apr 13, 2023 at 10:21
  • @aggregate1166877 it works for me (DEFAULT_FORWARD_POLICY="ACCEPT"), anyway you can list status by "systemctl status ufw.service". I had an issue with additional line after last COMMIT at before.rules file.
    – Marek-A-
    Nov 22, 2023 at 13:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .