Stop Broken LAN Port Forwards: Practical nftables SNAT, DNAT, Masquerade, and Hairpin NAT
说明与用途
正确配置 nftables NAT 使 LAN 客户端能够使用公网 IP,并在 WAN IP 更改后保持出站流量正常。包括 masquerade、snat、dnat、redirect 和 hairpin SNAT,使用专用链和映射。
问题
LAN clients cannot reach services via public hostname/IP due to incomplete NAT; outbound traffic fails when WAN IP changes; hard‑coded SNAT rules break.
结果
LAN clients can now use public hostname/IP; outbound traffic remains functional after ISP IP changes; NAT rules are stateful, persistent, and easier to maintain with maps.
工作流
- Enable IPv4 forwarding with sysctl and persist it
- Create nat table with postrouting chain for SNAT/masquerade and prerouting chain for DNAT
- Add masquerade rule for dynamic WAN or snat rule for static WAN
- Add dnat rule on prerouting for inbound services and corresponding forward filter rule
- Use redirect for local port rewrites if needed
- Create maps to collapse multiple dnat rules into single statements
- Add hairpin SNAT rule to translate source back to public IP for LAN clients
- Verify rules with nft list ruleset and test connectivity
- Persist rules in /etc/nftables.d/ and enable nftables service
- Rollback by restoring previous ruleset if issues arise
证据
Use dedicated NAT base chains on the right hooks and priorities
- 记录日期: 2026-09-05T18:15:18.258Z