Persistent Port 80 to 8080 Redirection on macOS: A Complete pf.conf Solution


2 views

Unlike Linux systems that use iptables/nftables, macOS employs the BSD-derived pf (packet filter) firewall. For developers needing to redirect web traffic from privileged port 80 to an alternative port like 8080, we need a persistent solution that survives reboots.

First, create or modify the packet filter configuration file:

sudo nano /etc/pf.conf

Add these rules before any existing "anchor" lines:

# Port redirection rules
rdr pass on lo0 inet proto tcp from any to 127.0.0.1 port 80 -> 127.0.0.1 port 8080
rdr pass on en0 inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080

Create a launch daemon to load the rules at boot:

sudo nano /Library/LaunchDaemons/com.apple.pfctl.plist

Insert this configuration:

<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.apple.pfctl</string>
    <key>ProgramArguments</key>
    <array>
        <string>/sbin/pfctl</string>
        <string>-e</string>
        <string>-f</string>
        <string>/etc/pf.conf</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

Load the new rules immediately:

sudo pfctl -ef /etc/pf.conf

Verify the redirection works:

curl -I http://localhost
telnet localhost 80

If the redirection fails:

  • Check for syntax errors: sudo pfctl -vnf /etc/pf.conf
  • Verify the target service is running on 8080: lsof -i :8080
  • Ensure pf is enabled: sudo pfctl -s info

Unlike Linux systems that use iptables, macOS employs the Packet Filter (PF) firewall system inherited from BSD. For permanent port redirection, we need to modify PF's configuration files directly.

Create or edit the main configuration file:

sudo nano /etc/pf.conf

Add these rules at the bottom (before any anchor references):

# Port redirection rules
rdr pass on lo0 inet proto tcp from any to 127.0.0.1 port 80 -> 127.0.0.1 port 8080
rdr pass on en0 inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080

To load these rules at startup:

sudo nano /System/Library/LaunchDaemons/com.apple.pfctl.plist

Modify the ProgramArguments array to include rule loading:

<array>
    <string>pfctl</string>
    <string>-e</string>
    <string>-f</string>
    <string>/etc/pf.conf</string>
</array>

After saving changes, test with:

sudo pfctl -f /etc/pf.conf
sudo pfctl -e

Verify the redirection:

curl -I http://localhost
telnet localhost 80

For development environments, you could also use:

# Using socat
brew install socat
socat TCP-LISTEN:80,fork TCP:localhost:8080

If the redirection doesn't work:

  1. Check System Integrity Protection status: csrutil status
  2. Verify no other services are using port 80: sudo lsof -i :80
  3. Test PF rules: sudo pfctl -vnf /etc/pf.conf