Route Traffic with Special Source/Destination on Ubuntu: A Tech Support Guide

Abstract: Configure policy routing on Ubuntu to direct traffic from specific source IPs through designated gateways using custom tables and ip rule commands.

Created: 2026-09-02 by

Routing traffic based on specific source or destination addresses on Ubuntu requires policy routing, which standard default routes cannot handle. You must configure separate routing tables and use ip rule commands to direct packets through distinct network interfaces. This approach ensures that traffic from a specific IP uses the correct gateway without disrupting general connectivity.

Understanding Policy Routing Concepts

Before applying changes, it is essential to understand how Linux handles packet forwarding. By default, all traffic uses the main routing table. Policy routing allows you to create additional tables and assign rules to them. These rules check the source address of incoming packets and decide which table to consult for the next hop. This mechanism is critical when you have multiple internet connections or need to isolate specific services to different networks. For more details on how network interfaces interact with these rules, see our guide on Ubuntu server network interfaces. Understanding the underlying interface configuration helps prevent conflicts when assigning static IPs to specific sources.

Configuring Static IP Addresses

Policy routing typically relies on static IP assignments for the source interfaces. Dynamic addressing via DHCP can complicate rule matching because IP addresses may change. First, identify the network interfaces involved in your setup. You can list them using the ip link show command. Next, assign static IP addresses to these interfaces. In modern Ubuntu versions, Netplan is the default configuration tool. However, Netplan does not natively support complex policy routing rules like ip rule directly in its YAML schema. Therefore, you often need to combine Netplan for basic interface configuration with systemd-networkd or manual scripts for the routing policies. If you are dealing with persistent connectivity issues after changing network settings, refer to our article on fixing Raspberry Pi internet issues after VPN changes, as similar principles apply to maintaining stable routes during configuration shifts.

Creating Custom Routing Tables

Linux supports up to 255 custom routing tables, indexed by ID. You need to define these IDs in the /etc/iproute2/rt_tables file. Open this file with a text editor and add new entries. For example, you might add:
# /etc/iproute2/rt_tables
#
# reserved values
255 local
254 main
253 default
0 unspec

# local routing tables
100 special_source
200 special_dest
Here, we created two tables: special_source (ID 100) and special_dest (ID 200). The numbers must be unique and not conflict with reserved IDs like 254 (main) or 255 (local). Once defined, the kernel recognizes these tables and can route packets to them based on rules.

Defining Rules and Routes

The core of policy routing lies in the ip rule and ip route commands. Rules determine which packets go to which table, while routes define how to reach destinations within that table. First, add a rule that matches your specific source IP address. Replace 192.168.1.100 with your actual source IP and eth0 with the appropriate interface name.
sudo ip rule add from 192.168.1.100 table special_source
This command tells the kernel: "If a packet originates from 192.168.1.100, look up the route in the 'special_source' table." Next, populate that table with the necessary routes. You need at least a default route pointing to the gateway for that specific connection.
sudo ip route add default via 10.0.0.1 dev eth0 table special_source
sudo ip route add 192.168.1.0/24 dev eth0 src 192.168.1.100 table special_source
The first line sets the default gateway for this table. The second line ensures that local subnet traffic remains on the interface. If you need to route based on destination rather than source, you would use ip rule add to <dest_ip> table ... instead.

Making Configuration Persistent

Commands executed via ip are lost upon reboot. To make them persistent, you should integrate them into your system's initialization process. On Ubuntu, creating a systemd service is the most reliable method. Create a file named /etc/systemd/system/policy-routing.service:
[Unit]
Description=Policy Routing Configuration
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/setup-policy-routing.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
Then, create the script /usr/local/bin/setup-policy-routing.sh containing all your ip rule and ip route commands. Ensure the script is executable with chmod +x. Finally, enable the service:
sudo systemctl enable policy-routing.service
sudo systemctl start policy-routing.service
This ensures that every time the network comes online, your custom routing policies are applied automatically.

Troubleshooting Common Issues

If your routed traffic does not work, verify the rules are active using ip rule show. Check if the source IP matches exactly. Also, ensure that the gateway specified in the custom table is reachable from the interface assigned to that table. Asymmetrical routing can cause problems where return traffic ignores your custom rules. To test connectivity, use ping -I <source_ip> <destination> to force the source address. For deeper diagnostics on why a device might not be reachable, consult our guide on troubleshooting Linux device not reachable during ping. This covers common firewall and routing blockers that affect policy-based setups.

Frequently Asked Questions

Can I use Netplan for all policy routing configurations?

No, standard Netplan YAML does not support ip rule directives directly. You should use Netplan for basic interface and IP assignment, then use systemd services or NetworkManager dispatcher scripts for the actual policy routing rules.

How do I verify which routing table a packet is using?

You can use ip rule show to see active rules. To trace a specific packet, use tcpdump or ss to monitor connections. Additionally, checking cat /proc/net/fib_trie can provide insights into how the kernel resolves addresses.

What happens if the primary interface goes down?

If the interface associated with your custom routing table fails, packets destined for that table will drop unless you have backup routes defined. It is good practice to include failover routes in your custom tables to maintain connectivity.

Is policy routing safe for production servers?

Yes, it is safe and widely used. However, incorrect configurations can lead to blackholes or asymmetric routing. Always test changes in a staging environment first and ensure you have console access to revert mistakes if network connectivity is lost.

Can I route traffic based on port numbers?

Standard Linux routing tables operate at Layer 3 (IP), not Layer 4 (ports). To route based on ports, you need to use iptables or nftables with mangle table rules to mark packets, and then use those marks in your ip rule statements.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More