mac 80端口映射 配置

时间:2023-03-08 23:02:15
mac 80端口映射 配置

mac 80端口映射 配置

macbook 下,要绑定 80 端口的话。

一种方式是用 root 权限启动,即 sudo 启动服务进程。但 sudo 指令存在一定的安全问题,能不使用的情况下我们都尽量不要使用。

所以这里给出另外一种解决方法

端口映射

  1. /etc/pf.anchors/ 目录下创建一份 xxx.forwarding (xxx 可以自定义)

    $ sudo touch /etc/pf.anchors/xxx.forwarding

    插入以下内容

    rdr pass inet proto tcp from any to any port 80 -> 127.0.0.1 port 10080
    rdr pass inet proto tcp from any to any port 443 -> 127.0.0.1 port 10443
  2. /etc/ 目录下创建一份 pf-xxx.conf (xxx 可以自定义)

    $ touch /etc/pf-xxx.conf

    插入以下内容 (xxx.forwarding 为 步骤1 创建的文件)

    rdr-anchor "xxx.forwarding"
    load anchor "xxx.forwarding" from "/etc/pf.anchors/xxx.forwarding"
  3. 执行 $ pfctl -vnf /etc/pf-xxx.conf 检查配置文件有没有问题 (非必须)

  4. 执行 $ sudo pfctl -F all -ef /etc/pf-xxx.conf 让端口转发生效

  5. 执行 $ sudo pfctl -s nat 查看是否生效

    若出现以下输出则证明端口转发成功

    rdr-anchor "xxx.forwarding" all
  6. 现在,启动服务进程,监听 10080 端口,访问下 http://localhost/ 试试吧 :)

开机自启动配置

端口映射的配置已经生效,但每次重启电脑后都要重新执行一次让端口转发生效的命令显然是很不方便的。所以我们要增加一份开机自启动的配置

  1. /usr/local/bin/ 目录下创建一份 enable-pf-xxx.sh (xxx 可以自定义)

    $ touch /usr/local/bin/enable-pf-xxx.sh

    插入以下内容 (pf-xxx.conf 为 端口映射步骤2 创建的文件)

    #!/bin/bash
    
    sleep 10
    /sbin/pfctl -ef /etc/pf-xxx.conf

    同时给 enable-pf-xxx.sh 提权

    chmod 755 /usr/local/bin/enable-pf-xxx.sh
  2. /Library/LaunchDaemons/ 目录下创建一份 com.xxx.pfctl.plist (xxx 可以自定义)

    $ touch /Library/LaunchDaemons/com.xxx.pfctl.plist

    插入以下内容 (com.xxx.pfctl 可自定义, enable-pf-xxx.sh 为 开机自启动配置步骤1 创建的文件)

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    <key>Label</key>
    <string>com.xxx.pfctl</string>
    <key>ProgramArguments</key>
    <array>
    <string>/usr/local/bin/enable-pf-xxx.sh</string>
    </array>
    <key>StandardOutPath</key>
    <string>/var/log/pf/access.log</string>
    <key>StandardErrorPath</key>
    <string>/var/log/pf/error.log</string>
    <key>RunAtLoad</key>
    <true/>
    </dict>
    </plist>

    ps: 生成的日志会存放在 /var/log/ 目录下

  3. 每次开机之后 mac 都会自动去执行 /Library/LaunchDaemons/目录下的文件。所以配置好了之后可以重启一下, 执行 端口映射步骤5 的命令查看自启动配置是否生效