Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a problem setting up iptables rules and routes on a Linux client for a scenario with DNAT and multiple gateways:

We have two gateways to the Internet. The first has a fixed IP, the second offers a better bandwidth. Both gateways do SNAT for outgoing traffic from our private network.

On the first gateway with the fixed IP I've set up port forwarding for port 22 so that all SSH traffic will be forwarded to my Linux client.

That works fine.

But only if I use this first gateway as default route on the Linux client.

When I switch the Linux client to the second gateway as default route, incoming SSH connections no longer work.

How can I setup the Linux client to send reply packets related to incoming SSH connections to the first gateway, but all other traffic to the second gateway?

share|improve this question
up vote 0 down vote accepted

I found a solution in the accepted answer to the question "Route return traffic to correct gateway depending on service".

I've implemented these rules on my Linux client:

# Default route is second gateway:
ip route add default via

# Create a routing table "FIXED" using our fixed IP gateway
echo "200 FIXED" >>/etc/iproute2/rt_tables
ip route add default table FIXED via

# Create a rule to route any packets marked "42" through FIXED:
ip rule add fwmark 42 table FIXED

# Finally, the iptables rule:
# Any outgoing traffic from source port 22 of my Linux client
# that has a destination inside our private network (
# is marked "42" (and therefore goes to FIXED):
iptables -t mangle -A OUTPUT ! -d \
                             -p tcp -m tcp --sport 22 \
                             -j MARK --set-mark 42
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.