Skip to content
VDS · 网络、IP 地址与域名

nftables:更复杂的规则

当 ufw 不再够用时:nftables 表和链的结构、可直接使用的工作配置、地址集合、速率限制和端口转发。

更新于 2026年8月23日

nftables 正是 ufw 底层所依赖的内核机制。当您需要命名地址集合、限速、按网卡设置不同策略或端口转发时,也就是说,当您的规则不再适用于“放行一个端口”这种场景时,就应该直接使用它。

您不需要同时使用这两个工具:切换之前,请用 ufw disable 关闭 ufw,否则规则会相互重叠,在排查问题时造成困扰。

结构

规则存放在表中,表包含链,链包含规则。链与数据包处理阶段(input、forward、output)绑定,并具有默认策略。

apt install -y nftables
systemctl enable --now nftables
nft list ruleset

可用配置

文件 /etc/nftables.conf:

#!/usr/sbin/nft -f
flush ruleset

table inet filter {
    set admins {
        type ipv4_addr
        elements = { 203.0.113.5, 198.51.100.7 }
    }

    chain input {
        type filter hook input priority 0; policy drop;

        iif lo accept
        ct state established,related accept
        ct state invalid drop

        ip protocol icmp icmp type echo-request limit rate 5/second accept

        tcp dport 22 ip saddr @admins accept
        tcp dport 22 ct state new limit rate 6/minute accept
        tcp dport { 80, 443 } accept
    }

    chain forward {
        type filter hook forward priority 0; policy drop;
    }

    chain output {
        type filter hook output priority 0; policy accept;
    }
}

应用并保存:

nft -c -f /etc/nftables.conf
nft -f /etc/nftables.conf
systemctl restart nftables

-c 参数仅检查语法,不会应用规则。请始终使用它:带有拼写错误的 drop 策略会切断访问,您将不得不通过 /hosting/vds/m/<id> 面板中的控制台重新进入。

地址集合与限速

命名集合可以随时修改,无需重新加载规则:

nft add element inet filter admins { 192.0.2.10 }
nft delete element inet filter admins { 198.51.100.7 }
nft list set inet filter admins

带超时的动态集合适合用于自定义封禁:

set blocked {
    type ipv4_addr
    flags timeout
    timeout 1h
}

转发与地址替换

如果内部运行着容器或隧道,就需要用到:

table ip nat {
    chain prerouting {
        type nat hook prerouting priority -100;
        tcp dport 8443 dnat to 10.10.0.2:443
    }
    chain postrouting {
        type nat hook postrouting priority 100;
        oifname "eth0" masquerade
    }
}

常见错误

错误后果解决方法
缺少 ct state established 规则对发出请求的回应被切断将其添加为第一条规则
忘记 iif lo accept本地服务和数据库异常放行回环接口
规则已应用但未保存重启后全部开放写入 /etc/nftables.conf
ufw 与 nftables 同时使用结果不可预测只保留一个工具

请在单独的会话中测试新规则集,不要关闭当前正在使用的会话。一个简单的保险措施:在后台执行 sleep 300 && nft flush ruleset —— 如果您把自己锁在外面,访问会自动恢复。

如果您不需要这些细节,请回到 ufw:它涵盖了大多数任务。