Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk11 min

How to Route VPS Traffic Through a VPN Using an OpenVPN Client

A practical Linux VPS guide to using OpenVPN client mode with redirect-gateway def1, preserving SSH through the original gateway, testing routes, fixing DNS, and choosing selective or policy routing.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To send a VPS’s outbound IPv4 traffic through an OpenVPN tunnel, add redirect-gateway def1 to the client configuration. OpenVPN installs two broad routes, 0.0.0.0/1 and 128.0.0.0/1, so the tunnel becomes the effective default route while the original default route remains available. Before reconnecting, add a host route for the public IP address of your SSH client through the VPS’s original gateway. Without that exception, SSH replies follow the VPN and the existing session normally stalls.

The safest rollout uses an out-of-band console or a second SSH session, a root-owned up script that recreates the SSH route whenever the tunnel connects, and explicit checks for routing and DNS after the change.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What you need before changing the route

This procedure assumes a Linux VPS running an OpenVPN client with administrative privileges. File locations and service names differ between distributions, so treat the paths below as examples and confirm the unit and configuration path used by your installation.

  • An out-of-band web console, serial console, or provider recovery access. Do not make a default-route change with your only management path.
  • A copy of the working OpenVPN client configuration.
  • The VPN provider’s client profile, including its remote endpoint, certificates, and authentication settings.
  • The VPS’s current IPv4 gateway and interface.
  • The public IPv4 address from which your SSH session originates.

Record the current route before starting:

ip -4 route show default
ip -4 route

A typical default-route line contains a gateway and device, for example default via 192.0.2.1 dev eth0. The address shown as the gateway is the next hop that must continue carrying SSH replies outside the tunnel.

#1 Best Overall
Sale
TP-Link AX1800 WiFi 6 Router (Archer AX21 V5) | Dual Band Wireless Internet, Gigabit, Easy Mesh, Works with Alexa - A Certified for Humans Device
  • DUAL-BAND WIFI 6 ROUTER: Wi-Fi 6(802.11ax) technology achieves faster speeds, greater capacity and reduced network congestion compared to the previous gen. All WiFi routers require a separate modem. Dual-Band WiFi routers do not support the 6 GHz band.
  • AX1800: Enjoy smoother and more stable streaming, gaming, downloading with 1.8 Gbps total bandwidth (up to 1200 Mbps on 5 GHz and up to 574 Mbps on 2.4 GHz). Performance varies by conditions, distance to devices, and obstacles such as walls.
  • CONNECT MORE DEVICES: Wi-Fi 6 technology communicates more data to more devices simultaneously using revolutionary OFDMA technology
  • EXTENSIVE COVERAGE: Achieve the strong, reliable WiFi coverage with Archer AX1800 as it focuses signal strength to your devices far away using Beamforming technology, 4 high-gain antennas and an advanced front-end module (FEM) chipset
  • OUR CYBERSECURITY COMMITMENT: TP-Link is a signatory of the U.S. Cybersecurity and Infrastructure Security Agency’s (CISA) Secure-by-Design pledge. This device is designed, built, and maintained, with advanced security as a core requirement.

From the SSH session, you can inspect the login source with:

who -m --ips

If the VPS is reached through a NAT gateway, the address shown here is the NAT’s public address, not your workstation’s private address. A host route to that public address protects every connection arriving from it, which may include other users behind the same NAT.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How redirect-gateway def1 changes routing

When the OpenVPN server supplies a redirect-gateway instruction, the client is told to send ordinary outbound traffic through the tunnel. The def1 form does this with two routes instead of deleting the existing 0.0.0.0/0 route:

Destination Purpose
0.0.0.0/1 Matches addresses from 0.0.0.0 through 127.255.255.255.
128.0.0.0/1 Matches addresses from 128.0.0.0 through 255.255.255.255.
VPN remote endpoint A more-specific route through the pre-existing gateway prevents the OpenVPN control connection from routing into its own tunnel.
Original default route Remains in the routing table, but is less specific than the two /1 routes.

Because a /1 route is more specific than a /0 route, nearly every IPv4 destination uses the VPN interface. The endpoint exception is essential: without it, the client could attempt to reach the VPN server through the tunnel that it is still trying to establish.

The original default route is also what lets you preserve SSH. A host route for the SSH client’s address is even more specific than either /1 route, so replies to that address leave through the original Ethernet interface and gateway.

Configure the OpenVPN client

1. Add the redirect and hook

Open the client profile used by your service and add these directives:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
redirect-gateway def1
script-security 2
up /etc/openvpn/add-ssh-route.sh

redirect-gateway def1 is the routing change. The script-security setting permits an external script to be called; the exact security levels and their semantics vary by OpenVPN version, so verify the accepted value in the manual for the version installed on your VPS. The up directive runs a command after the TUN/TAP device opens and before an optional OpenVPN user-ID change.

Rank #2
Sale
TP-Link ER605, Wired Gigabit VPN Router | Up to 3 WAN Ethernet Ports + 1 USB WAN, SPI Firewall SMB Router, Omada SDN Integrated, Load Balance, Lightning Protection
  • 【Five Gigabit Ports】1 Gigabit WAN Port plus 2 Gigabit WAN/LAN Ports plus 2 Gigabit LAN Port. Up to 3 WAN ports optimize bandwidth usage through one device.
  • 【One USB WAN Port】Mobile broadband via 4G/3G modem is supported for WAN backup by connecting to the USB port. For complete list of compatible 4G/3G modems, please visit TP-Link website.
  • 【Abundant Security Features】Advanced firewall policies, DoS defense, IP/MAC/URL filtering, speed test and more security functions protect your network and data.
  • 【Highly Secure VPN】Supports up to 20× LAN-to-LAN IPsec, 16× OpenVPN, 16× L2TP, and 16× PPTP VPN connections.
  • Security - SPI Firewall, VPN Pass through, FTP/H.323/PPTP/SIP/IPsec ALG, DoS Defence, Ping of Death and Local Management. Standards and Protocols IEEE 802.3, 802.3u, 802.3ab, IEEE 802.3x, IEEE 802.1q

Use a root-owned script in a directory writable only by root:

install -o root -g root -m 700 /dev/null /etc/openvpn/add-ssh-route.sh

2. Create an idempotent SSH-route script

The following example follows the common pattern of obtaining the current SSH source from who -m --ips, finding the existing default gateway, and replacing a single host route. It handles one IPv4 SSH source; adapt the address extraction if your login uses IPv6 or multiple simultaneous administrative sessions.

#!/bin/sh
set -eu

# Find the first IPv4 address printed for the current login.
SSH_IP="$(who -m --ips 2>/dev/null | awk '{for (i=1; i<=NF; i++) { gsub(/[()]/, "", $i); if ($i ~ /^[0-9]+(.[0-9]+){3}$/) { print $i; exit } }}')"

[ -n "$SSH_IP" ] || exit 0

DEFAULT_LINE="$(ip -4 route show default | awk 'NR == 1 { print; exit }')"
GATEWAY="$(printf '%sn' "$DEFAULT_LINE" | awk '{for (i=1; i<=NF; i++) if ($i == "via") { print $(i+1); exit }}')"
DEVICE="$(printf '%sn' "$DEFAULT_LINE" | awk '{for (i=1; i<=NF; i++) if ($i == "dev") { print $(i+1); exit }}')"

[ -n "$GATEWAY" ] || exit 1
[ -n "$DEVICE" ] || exit 1

ip -4 route replace "$SSH_IP/32" via "$GATEWAY" dev "$DEVICE"

Save the file, then test it from the provider console or while a second management session is available. The command is intentionally repeatable: if OpenVPN runs the hook again after a reconnect, ip route replace updates the same exception instead of creating duplicates.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

On systems that still use the legacy route utility, the equivalent operation is commonly written as route add -host <client-address> gw <original-gateway>. Use the syntax supported by your distribution and confirm the resulting route with ip route.

3. Start or restart the client carefully

Do not close the working SSH window. Start the client in the foreground first when possible:

openvpn --config /etc/openvpn/client/client.conf

Watch the log for a successful TLS connection, tunnel creation, and execution of the up script. If your distribution manages OpenVPN with systemd, use the client unit supplied by that distribution (often a template such as openvpn-client@name) rather than guessing a service name. Keep the console open until routing and SSH have been verified.

Verify that traffic and SSH take the intended paths

Inspect the complete route table

After the tunnel is established, run:

ip -4 route

You should see both /1 routes through the tunnel, the original default route through the physical interface, and a /32 route for the SSH source through the original gateway. The exact tunnel address, metric, and device name depend on the provider.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
GL.iNet GL-MT3000 Beryl AX Wi-Fi 6 Travel Router, 2.5G WAN, VPN, OpenWrt | Wi-Fi 6 dual band 574Mbps 2.4GHz plus 2402Mbps 5GHz, 2.5G WAN, gigabit LAN, USB 3.0
  • 【DUAL BAND AX TRAVEL ROUTER】Products with US, UK, EU Plug; Dual band network with wireless speed 574Mbps (2.4G)+2402Mbps (5G); 2.5G Multi-gigabit WAN port and a 1G gigabit LAN port; USB 3.0 port; Wi-Fi 6 offers more than double the total Wi-Fi speed with the MT3000 VPN Router.
  • 【VPN CLIENT & SERVER】OpenVPN and WireGuard are pre-installed, compatible with 30+ VPN service providers (active subscription required). Simply log in to your existing VPN account with our portable wifi device, and Beryl AX automatically encrypts all network traffic within the connected network. Max. VPN speed of 150 Mbps (OpenVPN); 300 Mbps (WireGuard). *Speed tests are conducted on a local network. Real-world speeds may differ depending on your network configuration.*
  • 【OpenWrt 21.02 FIRMWARE】The Beryl AX is a portable wifi box and mini router that runs on OpenWrt 21.02 firmware. It supports more than 5,000 ready-made plug-ins for customization. Simply browse, install, and manage packages with our no-code interface within Beryl AX's Admin Panel.
  • 【PROTECT YOUR NETWORK SECURITY】Our pocket wifi, unlike other vulnerable portable wifi hotspot for travel purposes supports WPA3 protocol–Preventive measures against password brute-force attacks; DNS over HTTPS & DNS over TLS–Protecting domain name system traffic and preventing data eavesdropping from malicious parties; IPv6–Built-in authentication for privacy protection, eliminating the need for network address translation.
  • 【VPN CASCADING AT EASE】Surpassing the mediocre performance of most VPN routers for home usage, the Beryl AX is capable of hosting a VPN server and VPN client at the same time within the same device, enabling users to remote access local network resources like Wi-Fi printers or local web servers, and accessing the public internet as a VPN client simultaneously.

Ask the kernel which interface it will use

Use a known public IPv4 address as a routing test:

ip -4 route get 8.8.8.8

The result should name the OpenVPN device, such as tun0. Test the management address separately:

ip -4 route get YOUR_SSH_SOURCE_ADDRESS

Replace YOUR_SSH_SOURCE_ADDRESS with the actual address shown by who -m --ips. The result should show the physical interface and the original gateway, not the tunnel. Do not leave the literal text in a production command; it is a description of the value to insert.

Check name resolution

Routing can appear correct while DNS fails. Test resolution with a normal system lookup, for example:

getent hosts example.com
resolvectl status

Review /etc/resolv.conf and the resolver service after enabling the redirect. Some VPN profiles push DNS settings; others do not. If the resolver points to a nameserver reachable only through the old path, or to a private address that the VPN cannot reach, ordinary applications may report that the internet is unavailable even though packet routing works.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test a second management connection

Open a new SSH connection from the same source and, if possible, from a different source. Keeping the original session open gives you a recovery path if the newly created route is wrong. A second source may not be covered by a single /32 exception, so add additional host routes or use a management subnet route when your operating model requires it.

Why SSH drops and how to recover

The existing session stalls immediately

The usual cause is that the server changed its default route while the SSH session was active. Packets arriving from your client still reach the VPS, but replies now match one of the /1 routes and enter the VPN. Your client is not expecting those replies from a different path, so the session hangs. From the console, identify the source address and add a route through the original gateway:

ip -4 route replace CLIENT_PUBLIC_IP/32 via ORIGINAL_GATEWAY dev ORIGINAL_DEVICE

Then confirm with ip -4 route get CLIENT_PUBLIC_IP. Replace each uppercase term with the values recorded before the change.

Rank #4
GL.iNet GL-SFT1200 Opal Travel Router, AC1200 Dual-Band Wi-Fi | AC1200 dual-band Wi-Fi, 3 gigabit ports, OpenWrt with OpenVPN and WireGuard, 30+ VPN services, pocket 145g
  • 【AC1200 Dual-band Wireless Router】Simultaneous dual-band with wireless speed up to 300 Mbps (2.4GHz) + 867 Mbps (5GHz). 2.4GHz band can handles some simple tasks like emails or web browsing while bandwidth intensive tasks such as gaming or 4K video streaming can be handled by the 5GHz band.*Speed tests are conducted on a local network. Real-world speeds may differ depending on your network configuration.*
  • 【Easy Setup】Please refer to the User Manual and the Unboxing & Setup video guide on Amazon for detailed setup instructions and methods for connecting to the Internet.
  • 【Pocket-friendly】Lightweight design(145g) which designed for your next trip or adventure. Alongside its portable, compact design makes it easy to take with you on the go.
  • 【Full Gigabit Ports】Gigabit Wireless Internet Router with 2 Gigabit LAN ports and 1 Gigabit WAN ports, ideal for lots of internet plan and allow you to connect your wired devices directly.
  • 【Keep your Internet Safe】IPv6 supported. OpenVPN & WireGuard pre-installed, compatible with 30+ VPN service providers. Cloudflare encryption supported to protect the privacy.

The route works once but disappears after a VPN failure

Routes created by an up hook are tied to that connection lifecycle. When the tunnel is torn down, the host route may disappear with the other OpenVPN routes. Configure the hook so it runs on every successful reconnect, and test by stopping and starting the client while watching ip -4 route. If your service manager does not rerun the hook on reconnection, use its documented reconnect or route-up mechanism instead.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The VPN endpoint itself becomes unreachable

def1 normally causes OpenVPN to install a specific route to its remote address through the old gateway. If that route is missing, inspect the log and route table before adding ad-hoc defaults. A wrong gateway, a changed network interface name, or a provider profile that supplies conflicting routes can all produce a loop. Restore the original configuration from the console, then reintroduce the redirect after confirming the endpoint route.

The script finds no SSH address

who -m --ips may return no address for a console login, may show IPv6, or may show a format different from the example. Run it manually, inspect its output, and adjust the extraction logic. Never install a script that silently adds a route to an empty or unintended value. For several administrators, consider explicit, reviewed host routes rather than guessing which login should be protected.

Only IPv6 traffic bypasses the VPN

The route examples above are IPv4. Check the IPv6 table separately with ip -6 route. If the VPS has IPv6 connectivity, determine whether the provider profile and your OpenVPN version supply an IPv6 redirect; do not assume that an IPv4 def1 change covers it. If your requirement is “all traffic,” test both address families and decide whether to disable unused IPv6, configure a supported IPv6 tunnel, or maintain an explicit IPv6 policy.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose selective routing when a full redirect is too broad

A full redirect is convenient when every outbound IPv4 connection should use the VPN. It is often the wrong choice for a server that must keep cloud control-plane traffic, monitoring, backups, or administration on the ordinary network. Selective routing avoids moving unrelated destinations.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Approach Traffic scope Setup effort Reconnect behavior
redirect-gateway def1 Almost all IPv4 destinations, with explicit exceptions such as SSH. Low to moderate; requires route exceptions and testing. Exceptions must be recreated when the tunnel reconnects.
Server-pushed destination routes Only networks or hosts named by the VPN server. Low if the server is under your control; otherwise coordinate with its administrator. Routes are normally supplied again on each connection.
route-nopull plus client routes Only routes you add locally; the server can still provide TUN/TAP properties. Moderate; you must enumerate every destination that belongs in the tunnel. Client route directives are reapplied on reconnect.
Policy routing Traffic selected by source, destination, mark, user, or interface. High; requires separate routing tables, rules, and careful failure handling. Rules and routes must survive service restarts and tunnel changes.

Ignore pushed redirects with route-nopull

Add route-nopull to the client profile when you want to reject routes pushed by the server while retaining other tunnel configuration. Then add only the required route directives or install equivalent routes after the tunnel comes up. This is safer than a full redirect when the VPS has a small, known set of destinations that must use the VPN.

Filter only the redirect instruction

For OpenVPN 2.4 and later, an OpenVPN community recommendation is to use pull-filter ignore redirect-gateway when the server pushes a redirect that you do not want. Support and exact behavior should be checked against the version installed on your VPS; do not combine this with assumptions from a different release. Unlike route-nopull, a filter can leave unrelated pushed options enabled.

Best Value
Sale
TP-Link Dual-Band AX3000 Wi-Fi 6 Wireless Gigabit Internet Router for Home | EasyMesh, VPN Clients & Server, HomeShield, OFDMA, MU-MIMO, USB 3.0, Secure by Design - Archer AX55
  • Next-Gen Gigabit Wi-Fi 6 Speeds: 2402 Mbps on 5 GHz and 574 Mbps on 2.4 GHz bands ensure smoother streaming and faster downloads; support VPN server and VPN client¹
  • A More Responsive Experience: Enjoy smooth gaming, video streaming, and live feeds simultaneously. OFDMA makes your Wi-Fi stronger by allowing multiple clients to share one band at the same time, cutting latency and jitter.²
  • Expanded Wi-Fi Coverage: 4 high-gain external antennas and Beamforming technology combine to extend strong, reliable, Wi-Fi throughout your home.
  • Improved Battery Life: Target Wake Time helps your devices to communicate efficiently while consuming less power.
  • Improved Cooling Design: No heat ups, no throttles. A larger heat sink and redefined case design cools the WiFi 6 system and enables your network to stay at top speeds in more versatile environments.

Use policy routing for complex servers

Policy routing is appropriate when, for example, only traffic generated by one service account, one source address, or one destination set should use the VPN. The general design is to prevent unwanted pulled routes, assign the OpenVPN client to a known interface, create a separate routing table with that interface’s gateway, and add rules selecting the traffic that belongs in that table. Keep the main table’s route to the VPN endpoint and your management addresses outside the policy table so the control connection and SSH remain reachable.

OpenVPN directives that matter here

route-gateway

route-gateway specifies the gateway used with client route directives. With dhcp, OpenVPN obtains the gateway from DHCP negotiation. If a provider profile supplies a tunnel gateway, inspect the connection log and use the value appropriate to that profile rather than copying an address from another VPN.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

up

The up command runs after the TUN/TAP device opens and before an optional --user UID change. That makes it suitable for installing a root-owned management route, provided the script itself is protected and tested. The exact ordering of other route operations can depend on the profile and OpenVPN version, so verify the resulting table instead of relying solely on hook timing.

script-security

External scripts are deliberately restricted by OpenVPN’s script-security setting. The example uses level 2 because that is the pattern used in common deployment guides, but the accepted levels and implications were not established here for every release. Consult the manual for your installed version and keep the script minimal, root-owned, and non-writable by the OpenVPN runtime user.

Operational checklist

  1. Open a provider console or establish a second SSH session.
  2. Back up the client profile and record the current default gateway and device.
  3. Record the SSH source address with who -m --ips.
  4. Add redirect-gateway def1 and a protected up hook.
  5. Start the client without closing the original session.
  6. Confirm the two /1 routes, the endpoint route, and the SSH /32 route.
  7. Run ip -4 route get for both a public test address and the SSH source.
  8. Check DNS resolution and the IPv6 table separately.
  9. Disconnect and reconnect the VPN to prove the management route is recreated.
  10. Test recovery from the console before declaring the change complete.

Rollback

If the VPS becomes unreachable, use the out-of-band console. Stop the OpenVPN client, remove the redirect and hook directives from the profile, and restore the saved configuration. If stale routes remain, inspect them with ip -4 route and remove only routes you can identify as belonging to the failed VPN session. Re-establish the ordinary default route using the provider’s documented network configuration, then test SSH before attempting the VPN again.

The essential design is simple: let redirect-gateway def1 carry ordinary IPv4 traffic through the tunnel, keep the VPN endpoint reachable through the original gateway, and pin every management source that must remain outside the tunnel with a more-specific route. Reapply those exceptions on every reconnect and verify DNS and both IP families rather than assuming a successful tunnel handshake means the VPS is fully reachable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.