OpenVPN Internet Routing on OpenVZ VPS

As far as I know, the iptables masquerade module is not compatible with OpenVZ. As a result, many guides online on how to route all traffic through an OpenVPN Tunnel do not work with OpenVZ, as they depend on the masquerade module of iptables. This IPTables rule:

iptables -t nat -A POSTROUTING -o venet0 -j SNAT --to-source XXX.XXX.XXX.XXX

where XXX.XXX.XXX.XXX is your VPS’s EXTERNAL IP address`

can be used instead. You can add these lines to your /etc/rc.local file so that they are run at boot. You will also need to edit your /etc/sysctl.conf file, and uncomment this line:

#net.ipv4.ip_forward=1

by removing the #, so that it looks like this:

net.ipv4.ip_forward=1

to enable ip forwarding. Since this file is loaded at boot, you can enable IP Forwarding on the fly by running:

echo 1 > /proc/sys/net/ipv4/ip_forward

through the command line.

I hope that this has helped someone – I know that I had to look through several guides online before I managed to get it working.