October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

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

A practical Linux VPS guide to routing outbound traffic through an OpenVPN client while keeping SSH reachable. It covers redirect-gateway def1, automatic host routes, reconnects, DNS checks, selective routing, policy routing, and rollback.
Length10 min Posted Quest giverVGSources Team

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.

To send a Linux VPS’s default IPv4 traffic through an OpenVPN tunnel, add redirect-gateway def1 to the client configuration. Before connecting, preserve a host route for the public IP of your SSH client through the VPS’s existing gateway. Without that exception, SSH replies follow the new VPN default route and the session usually stalls. The route must be recreated whenever the tunnel reconnects, and DNS should be tested after the change.

What the configuration changes

An OpenVPN client normally leaves the VPS’s existing default route in charge. The redirect-gateway directive changes that behavior by making traffic use the VPN interface. The def1 parameter installs two more-specific IPv4 routes, 0.0.0.0/1 and 128.0.0.0/1, instead of replacing the existing 0.0.0.0/0 route. Every IPv4 destination is covered by one of those two routes, while the original default route remains available for exceptions such as reaching the VPN server itself.

As an Amazon Associate I earn from qualifying purchases.

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.

OpenVPN also adds a route to the configured remote endpoint through the pre-existing gateway. That endpoint route prevents a loop in which the client would try to reach the VPN server through the tunnel that is being established. The exact route order can vary by OpenVPN and operating-system version, so inspect the live table rather than assuming it.

Why an existing SSH session disconnects

Suppose your workstation connects to the VPS at public address 203.0.113.44. Before OpenVPN starts, the VPS sends replies through its ordinary Internet gateway. After redirect-gateway def1 is applied, a packet destined for 203.0.113.44 matches 128.0.0.0/1 or 0.0.0.0/1 and is sent into the VPN. Your workstation is not on the tunnel, so the reply never arrives and the SSH connection appears frozen.

#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.

A host route with a /32 mask is more specific than either covering route. It tells the kernel to send only your SSH client’s address through the original gateway. This is the critical exception; merely leaving the old default route present is not enough because the two /1 routes are more specific.

Before you change the client

Keep an out-of-band recovery path

Use your hosting provider’s serial console, web console, or another independent administration path if one exists. Test that access before applying the change. If the VPN fails, you can remove the redirect directive or repair the route without depending on the SSH session you may have just interrupted.

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

Record the current network state

Run these commands in the current SSH session and save the output:

ip route
ip route show default
ip addr
printf 'SSH connection: %sn' "$SSH_CONNECTION"
who -m --ips

The first field of SSH_CONNECTION is normally the remote client’s address, followed by the client’s source port, the VPS address, and the VPS’s SSH port. who -m --ips is the pattern used by several Linux guides to discover the address associated with the current login; verify its output on your distribution, especially when more than one administrator is logged in.

Back up the .ovpn file

Copy the client profile before editing it. The profile may be under /etc/openvpn/, /etc/openvpn/client/, or a distribution-specific directory. Do not assume that a systemd unit uses the file you edited; check the unit or service status so the test uses the intended profile.

Configure full-tunnel routing

1. Add the redirect directive

Open the client profile and add:

redirect-gateway def1

Place it as a client-side directive in the profile. If the VPN server pushes its own redirect-gateway option, this explicit setting still documents the intended behavior; if you do not want the server’s routes, use the selective-routing methods described later.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

2. Add an SSH-route hook

OpenVPN’s up hook runs after the TUN/TAP device opens and before any configured user-ID change. A commonly used pattern enables scripts and calls a route script:

script-security 2
up /etc/openvpn/add-ssh-route.sh

The meaning and permitted levels of script-security should be checked against the manual for the OpenVPN version installed on your VPS; the level above is the setting used in the guide pattern from which this approach is commonly derived.

3. Create the route script

Create /etc/openvpn/add-ssh-route.sh with root ownership and executable permissions. This example discovers the logged-in SSH address and the gateway that exists when the script runs, then installs a host route:

#!/bin/sh
set -eu

SSH_IP="$(who -m --ips | awk 'NR == 1 {print $NF}')"
ORIGINAL_GW="$(ip route show default | awk 'NR == 1 {print $3}')"
ORIGINAL_DEV="$(ip route show default | awk 'NR == 1 {print $5}')"

if [ -z "$SSH_IP" ] || [ -z "$ORIGINAL_GW" ]; then
    echo "Could not determine SSH address or original gateway" >&2
    exit 1
fi

ip route replace "$SSH_IP/32" via "$ORIGINAL_GW" dev "$ORIGINAL_DEV"

Install it, for example, with:

chown root:root /etc/openvpn/add-ssh-route.sh
chmod 700 /etc/openvpn/add-ssh-route.sh

The script assumes that the first default route shown at hook time is the pre-VPN route. Confirm that assumption with ip route show default on your system. If who -m --ips returns no address, returns an IPv6 address, or lists a different login first, replace the automatic discovery with the known IPv4 address of your administration workstation and test the resulting route manually. Do not put a literal address in the profile unless that address is stable.

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

4. Test the script without restarting the tunnel

Run the script manually while the ordinary route is still active:

/etc/openvpn/add-ssh-route.sh
ip route get "$(printf '%s' "$SSH_CONNECTION" | awk '{print $1}')"

The route lookup should show the VPS’s original gateway and ordinary network interface, not the OpenVPN interface. If the command reports a missing gateway or the wrong interface, stop and correct the script before enabling the tunnel.

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.

5. Reconnect in a second SSH window

Keep the original session open. Start the OpenVPN client from the service manager or the command used by your distribution, then watch its log. In a second terminal, connect to the VPS again. This confirms both that new SSH connections work and that the exception is not limited to the first session.

After the tunnel is up, inspect the routes:

ip route
ip route get 1.1.1.1
ip route get <your-ssh-client-ip>

The first lookup should use the VPN interface and one of the two /1 routes. The SSH-client lookup should use the original gateway and device. Replace <your-ssh-client-ip> in the command with the actual address; angle-bracket notation is shown only to indicate a value you must supply.

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

Make the route survive reconnects

A host route installed by an up hook is associated with the current network state. If the VPN process exits, reconnects, or renegotiates in a way that recreates the interface, the exception may disappear. The script must run on every successful tunnel-up event, not only during boot.

Check the OpenVPN service logs after a reconnect and verify both routes again. If your service invokes the profile only once and leaves reconnection to another wrapper, place the hook in the profile that is actually reused. A separate startup script can also re-add the route, but it must run after the original gateway is available and whenever the tunnel is recreated.

If several administrators need uninterrupted access, install a /32 route for each stable public source address or use a controlled management network. A script that selects only the first result from who -m --ips protects one login, not every possible SSH client.

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

Verify Internet routing and DNS

Confirm the data path

  • Route decision: ip route get 1.1.1.1 should select the OpenVPN interface after the redirect is active.
  • SSH exception: ip route get <client-address> should select the original gateway.
  • Interface state: inspect ip addr show and the OpenVPN log to confirm that the TUN/TAP device remains up.
  • Application test: use a destination that your VPS is authorized to contact and compare the observed public address before and after the tunnel. A route change alone does not prove that the VPN provider accepts or forwards every protocol.

Check name resolution separately

One reported failure mode is that DNS stops working after redirect-gateway is enabled. Test DNS independently from raw IP routing:

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.
getent hosts example.com
resolvectl status 2>/dev/null || cat /etc/resolv.conf

Inspect the resolver addresses and the route to them. A resolver reachable only through the old network may no longer be accessible, while a resolver reachable through the VPN may require the VPN provider’s DNS settings. Correct the resolver configuration using your distribution’s normal resolver manager; do not assume that changing the default route automatically changes DNS servers.

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

Choosing full-tunnel or selective routing

Full tunneling is convenient when every outbound IPv4 connection from the VPS should use the VPN. It is not always the safest design: monitoring, package mirrors, control-plane endpoints, or management networks may need the original path. Selective routing avoids redirecting unrelated traffic.

Approach Traffic scope Setup effort Reconnect behavior When to choose it
redirect-gateway def1 plus SSH host route All IPv4 destinations except explicit exceptions Low to moderate; requires a reliable hook Host route must be recreated on reconnect The VPS should use the VPN as its ordinary egress path
Specific pushed or local routes Only listed destination networks Low when the destination list is stable Routes are normally reapplied with the tunnel Only a few services or networks belong in the VPN
route-nopull Only routes you add yourself; TUN/TAP properties can still be received Moderate; you must define required routes Reapplied by the client profile on reconnect You need to prevent server-pushed routes from changing the VPS default path
pull-filter ignore redirect-gateway Ignores a pushed redirect while allowing other pushed options Low, but version-dependent Handled on each connection OpenVPN 2.4 or later where this directive is supported and verified locally
Policy routing by VPN interface Traffic selected by source, user, mark, or destination rules High; requires routing tables and policy rules Rules and interface state must be maintained across reconnects Different applications or source addresses need different egress paths

Use explicit routes instead of a default redirect

An OpenVPN server or client can push or install routes for only the networks that should traverse the tunnel. This avoids the SSH return-path problem for destinations that are not selected, but you still need a management route if the selected network includes your administration address. Document every destination and verify it with ip route get.

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

Use route-nopull when server pushes are unwanted

route-nopull prevents the server from adding routes while still allowing the server to provide TUN/TAP-related settings. Add the routes you actually need in the client profile. The OpenVPN 2.6 manual documents this option; confirm behavior against the exact version installed on the VPS.

Filter only the redirect

For OpenVPN 2.4 and later, an OpenVPN community page recommends pull-filter ignore redirect-gateway as a way to reject a pushed redirect while accepting other pushed settings. Confidence in version-specific edge cases is lower than for the basic routing directives, so test the resulting route table on your installed release before relying on it in production.

Policy-route selected traffic

With policy routing, disable unwanted pulled routes, give the OpenVPN client its own routing table or interface rules, and direct only chosen sources or destinations through that table. This is more work than def1, but it avoids a single global default-route change and can support separate paths for services, users, or address ranges.

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.

Useful OpenVPN route options

Directive Purpose Operational note
redirect-gateway def1 Routes the IPv4 default space through two /1 routes Preserves the original default route but still requires management exceptions
route-gateway Sets the gateway used with client route directives dhcp can obtain it from DHCP negotiation; behavior depends on the platform
route Adds a destination route through the VPN or specified gateway Use a narrow network or /32 for an individual management address
up Runs a command after TUN/TAP opens Use an absolute script path and ensure permissions and execution policy are correct
route-nopull Stops server-pushed routes from being installed Define all required routes yourself

Troubleshooting branches

SSH freezes as soon as the tunnel connects

  1. Use the out-of-band console or a second session.
  2. Run ip route get <SSH-client-address>.
  3. If it selects the VPN interface, add or repair the /32 route through the original gateway.
  4. Confirm that the script runs on every tunnel-up event and that it identifies the correct login address.

The VPN connects but ordinary traffic still uses the old path

Check whether the profile contains route-nopull, a pull filter that ignores the redirect, or a later route with a more specific destination. Inspect ip route and the OpenVPN log rather than relying on the connection status alone.

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

The script cannot find a gateway

Run the script before changing the default route and compare its result with ip route show default. Some systems expose multiple defaults, metrics, or separate routing tables. Select the gateway and interface associated with the VPS’s ordinary public address, then make that choice explicit in the script.

DNS fails while IP connections work

Inspect /etc/resolv.conf or resolvectl status, test the resolver addresses directly, and ensure that the selected resolver is reachable through the active route. Restore the distribution’s resolver service if it was overwritten by a VPN helper.

The route works once but disappears later

Trigger a controlled VPN reconnect and repeat the two ip route get checks. If the /32 is gone, attach the script to the profile’s recurring up event or to the service wrapper that handles reconnection. A one-time manual route is not a persistent fix.

Rollback procedure

  1. Use the console or a still-working SSH session.
  2. Stop the OpenVPN client.
  3. Remove or comment out redirect-gateway def1, the up line, and the script-security line if they were added only for this hook.
  4. Restore the backed-up profile and restart the client only after ip route show default shows the expected ordinary gateway.
  5. Remove stale host routes with ip route del <client-address>/32 if necessary, then verify SSH and DNS.

Do not close your recovery console until a fresh SSH connection and a DNS lookup both succeed.

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

Operational checklist

  • Confirm the VPN provider supplies a compatible OpenVPN profile; compatibility is provider-specific.
  • Record the current default gateway, interface, and SSH client address.
  • Add redirect-gateway def1 only when full-tunnel IPv4 routing is intended.
  • Install and test the SSH host-route hook before restarting the client.
  • Verify the VPN endpoint route, the /1 routes, and the /32 management route.
  • Test DNS after the route change.
  • Re-test after a deliberate reconnect.
  • Keep an out-of-band console and a known-good profile for recovery.

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 quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

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.