FreeBSD port redirection for http requests

2.4k Views Asked by At

I've never used FreeBSD in my life but it's neccesary for me to deploy an HTTP API on FreeBSD. The API is deployed on port 3002.

What do I need to do to forward requests from port 80 to port 3002?

I tried adding this to my /etc/natd.conf file:

interface le0
use_sockets yes
dynamic yes

redirect_port tcp 192.168.1.8:80 192.168.1.8:3002

I also have this in my /etc/ipfw.rules file:

 ipfw add 1000 fwd 127.0.0.1,80 tcp from any to any 3002

When I run ipfw -q -f flush I get:

 ipfw: setsockopt(IP_FW_XDEL): Protocol not available

I don't know what any of this means, but it's not working.

Can somebody please tell me (in simple newbie terms) how to forward requests from 80 to 3002 in FreeBSD?

(I'm assuming port 80 is both open and the default port for HTTTP requests on a brand new FreeBSD installation)

4

There are 4 best solutions below

0
On BEST ANSWER

The easiest way would be to use Nginx or HAproxy to listen on port 80 and then forward/proxy your requests to your API, by doing this you could also benefit from terminating SSL port 443 and just forward traffic to your API

For example to install nginx:

# pkg install nginx-lite

Then edit the /usr/local/etc/nginx/nginx.conf and use this in the server section:

server {
    listen 80 default_server;
    server_name _;

    location / {
        proxy_pass http://127.0.0.1:3002;
        proxy_http_version 1.1; # for keep-alive
        proxy_redirect off;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

This will forward the request to your API on port 3002 without the need to use NAT or any firewall like ipfw or pf, also works if you have your app running within a jail.

0
On

almost done !!!!

should be

[was] ipfw add 1000 fwd 127.0.0.1,80 tcp from any to any 3002

ipfw add 1000 allow ipv4 from any to 127.0.0.1 via eth2

ipfw add 1010 fwd 127.0.0.1,3002 ipv4 from any to any 80,443 via eth2

2
On

Remember you need to put in /etc/rc.conf: gateway_enable="YES".You may also need to create a pipe(check ipfw man), and load a dummynet module.

0
On

In my opinion an easier option would be to use PF. Let me quote an example from the handbook https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/firewalls-pf.html

... redirection and NAT rules need to be defined before the filtering rules. Insert this rdr rule immediately after the nat rule:

rdr pass on $int_if proto tcp from any to any port ftp -> 127.0.0.1 port 8021

FWIW, I've published Ansible role to configure PF https://galaxy.ansible.com/vbotka/freebsd-pf/