When you are connected to your first server (SERVER1) and initiate a VPN connection to a second server (VPN Server), you may lose the SSH connection with SERVER1. This issue arises because the default OpenVPN configuration routes all outgoing traffic through the VPN server. Here, we provide solutions to maintain your SSH connection.
Terminology
- PC: The device from which the connection is made.
- SERVER1: Your first server.
- Second Server: Your VPN server.
Solution 1: Routing Traffic Through PC
To ensure your traffic goes directly through your PC and not the VPN, add your PC IP route. This method allows you to connect to your server only from the device's IP address that you specify.
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
Note: Replace PC-IP
with the IP address of your device from which you are trying to connect.
Solution 2: Advanced Users - Routing Specific Traffic
Mark the traffic to specific ports to be routed directly to the server (not through VPN) using iptables rules.
For Container and Storage VPS:
Disable rp_filter
:
sysctl -w net.ipv4.conf.venet0.rp_filter=0
Create iptables rules:
iptables -A OUTPUT -t mangle -p tcp -m 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 -A OUTPUT -t mangle -p tcp -m 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 eth0 table 3
Note: You can change the port number 22
to another port like 80
or 443
if you want other services on SERVER1 to be accessible from outside.
Additional Configuration: Routing Specific IP or Port
To route SERVER1's traffic directly to a specific IP (or port) and use VPN for all other traffic, create these iptables rules. This example is for Container and Storage VPS:
iptables -A PREROUTING -p tcp --dport 22 -t mangle -j MARK --set-mark 3
iptables -A POSTROUTING -t nat -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
Note: Replace SERVER1-IP
with the IP address of SERVER1.
By following these solutions, you can maintain your SSH connection to SERVER1 while connected to a VPN on the second server.