Search code examples
freebsdportforwardingsetsockoptipfw

FreeBSD port redirection for http requests


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)


Solution

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