Skip to main content

How to connect to VPN from your server when SSH connection is lost?

In this article we will provide solutions to the issue where you are connected to your first server and initiate a VPN connection to the second server but get disconnected.

Updated over a week ago

Terminology used

  • PC – the device from which the SSH connection is made

  • SERVER1 – your first server

  • Second Server – your VPN server

1. First Solution

To ensure your SSH traffic continues to go directly through your PC and not through the VPN, add a route for your PC’s IP address.
You will be able to connect to your server only from the device’s IP that you include.
Use the command below while connected to your VPS via SSH.

For Container and Storage VPS:

ip r a PC-IP/32 dev venet0

For Linux VPS:

ip r a PC-IP/32 via 169.254.0.1 dev enc3

Replace PC-IP with the public IP address of the device from which you’re connecting via SSH.

2. Second Solution (for Advanced Users)

In the PREROUTING chain, mark traffic for a specific port (such as SSH) to be routed directly to the server instead of through the VPN.

For Container and Storage VPS:

Disable rp_filter:

sysctl -w net.ipv4.conf.venet0.rp_filter=0

Create iptables rules:

iptables -t mangle -A OUTPUT -p tcp --sport 22 -j MARK --set-xmark 3
ip rule add fwmark 3 table 3
ip r a default dev venet0 table 3

For Linux VPS:

Create iptables rules:

iptables -t mangle -A OUTPUT -p tcp --sport 22 -j MARK --set-xmark 3
ip rule add fwmark 3 table 3
ip r a default via 169.254.0.1 dev ens3 table 3

If you want to allow access on a port other than SSH (for example 80 or 443), replace port 22 in the iptables rules above with your chosen port number.
This will make that service accessible directly, bypassing the VPN route.

Optional: Route only SSH traffic outside the VPN

If you want all other traffic to use the VPN except SSH connections, create the following rules (example for Container/Storage VPS):

iptables -t mangle -A PREROUTING -p tcp --dport 22 -j MARK --set-mark 3 
iptables -t nat -A POSTROUTING -m mark --mark 3 -j SNAT --to-source SERVER1-IP
ip rule add fwmark 3 table 3
ip r a default dev venet0 table 3

Replace SERVER1-IP with your server’s public IP address.

Did this answer your question?