1) Enable IPv4 forwarding (host must route traffic to VPS)
Optional permanent via /etc/sysctl.conf:
echo 1 > /proc/sys/net/ipv4/ip_forward
Optional permanent via /etc/sysctl.conf:
net.ipv4.ip_forward = 1
2) Allow forwarding for established/related connections
iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPTThis allows return traffic from VPS to WAN to pass through.
3) Forward new connections to VPS (example: SSH)
# Replace placeholders: #= host public IP # = private IP of VPS # = 22 or custom iptables -t nat -A PREROUTING -p tcp -d --dport -j DNAT --to-destination : iptables -A FORWARD -p tcp -d --dport -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT
4) Forward HTTP/HTTPS to VPS
# HTTP example iptables -t nat -A PREROUTING -p tcp -d <WAN_IP> --dport 80 -j DNAT --to-destination <VPS_IP>:80 iptables -t nat -A PREROUTING -p tcp -d <WAN_IP> --dport 443 -j DNAT --to-destination <VPS_IP>:443 iptables -A FORWARD -p tcp -d <VPS_IP> --dport 80 -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT iptables -A FORWARD -p tcp -d <VPS_IP> --dport 443 -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT
5) Masquerade (SNAT) for outbound traffic from VPS
# Replace <VPS_SUBNET> with your VPS network, e.g., 10.0.0.0/24 iptables -t nat -A POSTROUTING -s <VPS_SUBNET> -o eth0 -j MASQUERADEThis makes VPS traffic appear to come from the host’s WAN IP for Internet access.
6) Optional: default DROP policy for security
iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPTAlways add explicit allow rules for services you need before applying DROP.
7) Logging dropped packets (optional for monitoring)
iptables -A INPUT -j LOG --log-prefix "IPTables-Dropped: " --log-level 4 iptables -A FORWARD -j LOG --log-prefix "IPTables-FWD-Dropped: " --log-level 4
Notes:
- Always test in a lab environment before applying to production.
- Use placeholders (<VPS_IP>, <WAN_IP>, <VPS_SUBNET>) — never copy exact commands blindly.
- Maintain an open SSH session to avoid locking yourself out while testing firewall rules.
- Use conntrack state rules to allow return traffic without opening broad ports.
