Skip to content

ubuntu利用iptables做本机的端口转发

Tags:

问题

因为微基禁止了http转发,所以用443端口作为转发目的地失效了。

解决方案

所以在vps上将入口端口变成4443,所有访问4443的流量全部转至443. 反之亦然。

# 开启转发功能
sed -i.bak "s|(#)net.ipv4.ip_forward.*=.*0|net.ipv4.ip_forward = 1|g" /etc/sysctl.conf
grep -i 'net.ipv4.ip_forward.*=.*1' /etc/sysctl.conf
sysctl -p  #使数据转发功能生效

# 外网访问4443端口的数据转发到443端口 - 这是双向的
iptables -t nat -A PREROUTING -p tcp --dport 11443 -j REDIRECT --to-ports 443
iptables -t nat -A PREROUTING -p tcp --dport 22443 -j REDIRECT --to-ports 443
iptables -t nat -A PREROUTING -p tcp --dport 33443 -j REDIRECT --to-ports 443
iptables -t nat -A PREROUTING -p tcp --dport 44443 -j REDIRECT --to-ports 443
iptables -t nat -A PREROUTING -p tcp --dport 55443 -j REDIRECT --to-ports 443

# save rules
iptables-save > /etc/iptables.rules.v4

# 确保重启后仍然有效
iptables-restore <  /etc/iptables.rules.v4
cat > /etc/systemd/system/restore-iptables-rules.service <<EOF
[Unit]
Description = Apply iptables rules
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'iptables-restore <  /etc/iptables.rules.v4'

[Install]
WantedBy=multi-user.target
EOF

systemctl enable --now restore-iptables-rules.service

删除

ubuntu中iptables重启生效:
查看nat规则,并显示行号
iptables -t nat --list --line-number

删除一条nat 规则 删除SNAT规则
iptables -t nat -D POSTROUTING 1
iptables -t nat -D POSTROUTING 7

Leave a Reply

Your email address will not be published.