Forwarding Ports in OS X/MacOS
TweetUpdate: I have tested this with MacOS Sierra and it works for me!
I forward local ports on my OS X machines using pfctl so that I can use traditional ports for HTTP and HTTPS with Vagrant without having to start vagrant with root privleges. Recently when I updated to OS X El Capitan (10.11) I noticed that my port forwards stopped working.
Previously I had followed some of the steps in this gist, but all of those changes had been wiped out with the upgrade. When I tried to re-apply them, a new feature called System Integrity Protection (SIP) prevented me from editing some necessary files. Also, since all of my changes had been wiped out with this upgrade, I wanted to try to keep my changes out of existing system files as much as possible in the hopes that they won’t be wiped out with the next upgrade.
Creating an anchor file
The first file we need to add is an anchor file. This defines the ports we want to forward. Create the file in
/etc/pf.anchors/<CUSTOM NAME>
. You can add one or many lines of the following format:
Testing the anchor file
To test the anchor file, run the following command.
The ports won’t actually be forwarded yet, this just checks the validity of your anchor file. If you see output that looks something like the below, with no errors, you’re good.
Creating a pfctl config file
Once your anchor file checks out, you need to add a pfctl config file. Create this file under /etc/pf-<CUSTOM
NAME>.conf
and add the following contents.
Testing the config file
You can start pfctl using the below command. This will forward the ports according to your rules.
To stop forwarding ports run the same command, replacing the e
option with d
.
Forwarding ports at startup
You can use the commands above to start port forwarding on demand if you wish, otherwise if (like me) you want to
forward ports automatically at startup you can create a launchctl plist file. Create a file under
/Library/LaunchDaemons/com.apple.pfctl-<CUSTOM NAME>.plist
with the following contents:
Add the file to startup using the following command:
Example
You can find an example here that forwards port 80 to 4000 and 443 to 4001.
Credits
Hopefully this was helpful. Thanks to kujohn for creating the excellent gist that worked so well for me previously.