gpt-4o 写的,我润色润色,好笑的是找了一万种解决方案,结果最后 AI 写的是唯一正常工作的

    Openwrt 23.05

    创建回环配置脚本

    因为对我来说,我所有在外部访问的服务实际会通过子域名区分,在内网被反向代理,所以我只需要配置一个端口就行,有多个的话应该依葫芦画瓢就行

    注意修改 internal_ipport

    cat << 'EOF' > /etc/nat-loopback.sh
    #!/bin/sh
    
    # Get current public IP
    public_ip=$(curl -s 4.ipw.cn)
    
    # Internal server IP and port
    internal_ip="192.168.31.1"
    port="66666"
    
    # Flush existing rules to avoid duplication
    iptables -t nat -F PREROUTING
    iptables -t nat -F POSTROUTING
    iptables -F FORWARD
    
    # Add NAT loopback rules
    iptables -t nat -A PREROUTING -d $public_ip -j DNAT --to-destination $internal_ip
    iptables -t nat -A POSTROUTING -s $internal_ip -j MASQUERADE
    iptables -A FORWARD -d $internal_ip -p tcp --dport $port -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT
    EOF

    然后授予运行权限

    chmod +x /etc/nat-loopback.sh

    防火墙模块

    这一步不一定需要,但可能会因为缺模块导致无法工作,如果直接运行 /etc/nat-loopback.sh 没问题,就没必要走这一步

    opkg update
    opkg install ip-full iptables-mod-extra kmod-ipt-nat kmod-ipt-extra kmod-ipt-conntrack kmod-nf-conntrack

    安装完后重启防火墙

    /etc/init.d/firewall restart

    测试

    直接执行这个指令文件就行

    /etc/nat-loopback.sh

    如果没有报错,就尝试访问之前因为没有配置好环回导致出问题的地址,如果也正常,就可以把这个指令加到计划任务里了(因为涉及到获取公网IP,你要是买的固定IP算我没说)

    */5 * * * * /etc/nat-loopback.sh

    Openwrt 18.06

    依葫芦画瓢,缺一些模块的话自己上网找下

    #!/bin/sh
    
    # NAT Loopback Variables
    INTERNAL_IP="192.168.31.1"
    PORT="66666"
    
    CURRENT_IP=$(curl -s http://4.ipw.cn)
    
    # Check if PUBLIC_IP variable is set
    if [ -z "$PUBLIC_IP" ]; then
        PUBLIC_IP=$CURRENT_IP
    fi
    
    echo "Current IP: $CURRENT_IP"
    echo "Public IP: $PUBLIC_IP"
    
    if [ "$CURRENT_IP" != "$PUBLIC_IP" ]; then
        echo "Updating NAT loopback rules"
    
        # Clear existing NAT loopback rules
        iptables -t nat -D PREROUTING -d $PUBLIC_IP -p tcp --dport $PORT -j DNAT --to-destination $INTERNAL_IP:$PORT 2>/dev/    iptables -t nat -D POSTROUTING -d $INTERNAL_IP -p tcp --dport $PORT -j MASQUERADE 2>/dev/null
    
        # Update PUBLIC_IP
        PUBLIC_IP=$CURRENT_IP
    
        # Add updated NAT loopback rules
        iptables -t nat -A PREROUTING -d $PUBLIC_IP -p tcp --dport $PORT -j DNAT --to-destination $INTERNAL_IP:$PORT
        iptables -t nat -A POSTROUTING -d $INTERNAL_IP -p tcp --dport $PORT -j MASQUERADE
    
        # Verify rules
        echo "Current iptables rules:"
        iptables -t nat -L -v -n
    fi