Search code examples
node.jsmacosportforwarding

Node.js Express setup proxy for development environment, avoid localhost in url for Mac OS X


I want to setup my dev environment so that all requests from www.dev.com in my browser are routed to localhost:8080.

I added 127.0.01 www.dev.com in my /etc/host, but it doesn't do the port forwarding. If I go to http://www.dev.com:8080/ it works, but I want/need to use http://www.dev.com/ instead, which is closer to the actual production environment.

How do I do that? I tried several solutions like nginx, but I don't like it, I'd prefer it to be "scriptable", so that any other developer can use it directly. I'm using Express.js with Node.

I read through Assigning a domain name to localhost for development environment on Mac OS X with node.js but it actually doesn't explain the port-forwarding part.


Solution

  • You can use Mac port forwarding. Binding to port 80 requires root privileges (anything below 1024(?) needs root) and it's probably best not to run a development application with root.

    You can use pfctl port forwarding

    e.g. To forward port 80 to 8080

    echo "rdr pass inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080" | sudo pfctl -ef -
    

    source: https://salferrarello.com/mac-pfctl-port-forwarding/

    You can also use ipfw (Not available on El Capitan)

    sudo ipfw add 100 fwd 127.0.0.1,8080 tcp from any to any 80 in