How to redirect requests on port 80 to localhost:3000 using nftables?

stackhatter asked:

I would like for network traffic that arrives on 192.168.0.1:80 to be redirected to 127.0.0.1:3000. And, I would like the mapping of the response to be handled as well. My complete NAT and Filter table rules are pasted below.

I am able to received connections on port 80. However, I have been unable to redirect the traffic to localhost:3000.

add table inet filter
add chain inet filter input { type filter hook input priority 0; policy accept; }
add chain inet filter forward { type filter hook forward priority 0; policy accept; }
add chain inet filter output { type filter hook output priority 0; policy accept; }
add rule inet filter input ct state related,established  counter accept
add rule inet filter input ip protocol icmp counter accept
add rule inet filter input iifname "lo" counter accept
add rule inet filter input ct state new  tcp dport 80 counter accept
add rule inet filter input ct state new  tcp dport 4489 counter accept
add rule inet filter input ct state new  tcp dport 8080 counter accept
add rule inet filter input iifname "tun0" ct state new  tcp dport 139 counter accept
add rule inet filter input iifname "tun0" ct state new  tcp dport 445 counter accept
add rule inet filter input ct state new  udp dport 1194 counter accept
add rule inet filter input counter reject with icmp type host-prohibited
add rule inet filter forward counter reject with icmp type host-prohibited
add table nat
add chain nat prerouting { type nat hook prerouting priority -100; }
add chain nat postrouting { type nat hook postrouting priority 100; }
add rule nat prerouting redirect
add rule nat prerouting tcp dport 80 redirect to 3000
add rule nat prerouting iifname eth0 tcp dport { 80, 443 } dnat 127.0.0.1:3000
add rule nat postrouting oifname eth0 snat to 192.168.0.1

My answer:


You can use iptables-translate if you already have a functioning iptables rule and want to see its nftables equivalent.

For example, a functioning iptables rule for this redirect would be:

-t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3000

Feed that to iptables-translate and you get:

[[email protected] ~]# iptables-translate -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3000
nft add rule ip nat PREROUTING tcp dport 80 counter redirect to :3000

No other nat rules should be needed for this, though it sounds like you might have other redirects you want to put in place also. Do the same for them.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.