Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon 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×
FREEDOM251

Freedom251 › Blog › firewall

How to Configure SNAT With iptables on a Linux Server

By Freedom251 Team · · 10 min read

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

To let a private IPv4 subnet reach external networks through a Linux gateway, enable IPv4 forwarding and add a narrowly scoped rule to the nat table’s POSTROUTING chain. Use SNAT when the gateway has a stable public address; use MASQUERADE when the outgoing address changes. NAT alone is not a firewall policy: the filter table’s FORWARD chain must also permit the traffic, return packets must route back through the gateway, and the rule must be saved using your distribution’s supported firewall-management method.

What SNAT does and where the rule belongs

Source network address translation changes the source address on packets leaving a private network. A client such as 192.0.2.25 can send a connection toward the internet, while the upstream network sees the gateway’s public address, such as 198.51.100.10. The gateway records the connection mapping and rewrites returning packets back to the internal client.

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.

With iptables, source NAT is configured in the nat table, normally in POSTROUTING, after the kernel has selected the outgoing route. The extension documentation permits the SNAT target in the POSTROUTING and INPUT contexts and in user-defined chains called from those contexts. For an ordinary gateway, POSTROUTING is the appropriate place because the outgoing interface and route are known there.

A minimal fixed-address rule has five important parts: the table, chain, source match, egress-interface match, and translated source address.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
sudo iptables -t nat -A POSTROUTING 
  -s 192.0.2.0/24 -o eth0 
  -j SNAT --to-source 198.51.100.10

This example translates only packets from 192.0.2.0/24 that leave through eth0. Replace every example address and interface with values actually assigned to your server; the documentation ranges above are examples, not production addresses.

Before changing anything: map the gateway

Write down the topology before entering a rule. You need to know which interface faces the private clients, which interface faces the upstream network, the internal source subnet, and the public address that should appear on translated traffic.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Item Example What to confirm
Private subnet 192.0.2.0/24 The clients’ actual IPv4 network and prefix length
Private-side interface ens1 The interface connected to the clients or internal switch
Egress interface eth0 The interface whose route leads to the upstream network
Stable translated address 198.51.100.10 An address assigned to the server and usable upstream
Gateway route Upstream default route The server can itself reach the intended destination

Do not infer the public address from a client configuration. The value passed to --to-source must be an address the gateway owns or is explicitly allowed to use upstream. If the server has several addresses, choose the one whose return path and upstream policy are correct.

Prerequisites: forwarding, addressing and policy

Enable IPv4 forwarding

A Linux host does not automatically route packets between interfaces. IPv4 forwarding must be enabled before it can act as a gateway. Red Hat’s firewall guidance includes net.ipv4.ip_forward=1 as part of an IPv4 NAT setup.

sudo sysctl -w net.ipv4.ip_forward=1

The command changes the running kernel setting. To retain it after a reboot, place the setting in the persistent sysctl configuration supported by your distribution and reload that configuration using the distribution’s normal procedure. The exact file and service differ among distributions, so do not assume a single universal persistence command.

Check the active value before testing:

sysctl net.ipv4.ip_forward

The result should show net.ipv4.ip_forward = 1. If it is 0, NAT rules may exist and counters may remain unchanged because the host is not forwarding the client packet.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Confirm both interfaces and routes

Verify that the private interface has an address in the client subnet and that the egress interface has the stable address or receives the dynamic address you expect. Also verify that the Linux server itself can reach the destination. SNAT cannot repair a missing upstream route, an incorrect default gateway, or a disconnected interface.

Separate translation from filtering

The nat table changes addresses; it does not by itself authorize forwarding. The filter table’s FORWARD policy can still reject packets. Review the active forwarding policy and add narrowly scoped allow rules through the firewall system used by your distribution. There is no single filter rule that is portable across every host because existing policies, connection tracking, and firewall managers differ.

Configure SNAT for a stable public address

Use SNAT when the address that should represent the private clients is stable. Append the rule to POSTROUTING:

sudo iptables -t nat -A POSTROUTING 
  -s 192.0.2.0/24 -o eth0 
  -j SNAT --to-source 198.51.100.10

Interpret the command from left to right:

  • -t nat selects the network-address-translation table.
  • -A POSTROUTING appends the rule to the post-routing chain.
  • -s 192.0.2.0/24 limits translation to the intended private subnet.
  • -o eth0 limits it to packets leaving the specified interface.
  • -j SNAT selects source NAT.
  • --to-source 198.51.100.10 supplies the source address visible upstream.

Matching the source network and egress interface is important. A rule without those constraints can translate unrelated traffic from the server or another internal network. Add further matches only when your design requires them, such as a protocol or destination restriction. Narrow matching makes the rule easier to audit and reduces unintended side effects.

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

Use MASQUERADE when the egress address is dynamic

Choose MASQUERADE when the outgoing interface receives an address that can change, as with many dynamically assigned uplinks. MASQUERADE uses the outgoing interface’s current address rather than a manually specified fixed address.

sudo iptables -t nat -A POSTROUTING 
  -s 192.0.2.0/24 -o eth0 
  -j MASQUERADE

The source-subnet and interface matches have the same purpose as in the SNAT example. The difference is how the translated address is selected.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
Situation Preferred target Reason
Stable, explicitly assigned public address SNAT --to-source ... The translation states the intended address directly.
Address changes on the outgoing interface MASQUERADE The interface address is used automatically.

The iptables extension documentation recommends SNAT for static addresses and MASQUERADE for dynamically assigned addresses. The Debian nftables documentation describes masquerading as a special form of SNAT that always translates to the outgoing interface’s IP address. If your address is stable, explicit SNAT makes the configuration and troubleshooting result clearer.

Understand connection-oriented behavior

SNAT is connection-oriented. The target applies the source change to the connection’s future packets, and processing does not continue through later rules for that target. In practice, the first packet establishes a translation; subsequent packets in that flow use the recorded mapping rather than being independently translated by every rule evaluation.

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

The target can support source-port ranges and port-randomization options for protocols for which those options are valid. Use such options only when you have a concrete port-collision or allocation requirement and have confirmed that your installed iptables version and target support the requested behavior. A plain address-only rule is the correct starting point for ordinary outbound access.

Because mappings are per connection, changing or deleting a rule does not retroactively rewrite an already established flow. Start a new client connection after modifying the rule when testing a change. Existing flows may continue, fail, or retain their prior mapping according to connection-tracking state.

Permit the forwarded traffic separately

After adding NAT, inspect the filter table’s FORWARD chain and its default policy. A common failure pattern is a NAT counter that increases while the client still receives no response: the packet reached the NAT rule, but the forwarding policy rejected it or the return traffic was blocked.

Design filter rules around your actual policy rather than copying a catch-all example. At minimum, identify:

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.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
  • Which private source subnet may leave through the egress interface.
  • Which destinations and protocols are permitted.
  • Whether replies belonging to established connections are allowed back toward the private interface.
  • Whether the host has a default-deny policy that requires explicit forwarding rules.

Use the firewall manager supported by your distribution when it owns the filter configuration. Direct iptables commands can coexist badly with a manager that reloads its own rules, so determine which component is authoritative before making the configuration permanent.

Make the configuration survive a reboot

Rules entered with iptables are runtime state unless your distribution saves and restores them. Persistence is distribution-specific: the available service, configuration file, and reload procedure vary. The documentation establishes the need to configure forwarding and NAT but does not define one universal save/restore service.

Use this sequence:

  1. Identify whether your host uses a distribution firewall manager or a supported iptables rule-save service.
  2. Store the forwarding setting in the persistent sysctl configuration used by that system.
  3. Save the NAT and filter rules through the supported mechanism, not an ad-hoc script that may run too late during boot.
  4. Reboot a maintenance system, or deliberately reload the firewall, and verify that the rules and forwarding state return.
  5. Test a new connection from a private client after restoration.

Do not report a successful interactive test as proof of persistence. A gateway can work until reboot while having no saved NAT rule at all.

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

Inspect rules and test a real client flow

Verification should cover configuration, counters, forwarding, filtering, and return routing. Listing the active NAT table with verbose counters is a useful first check:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo iptables -t nat -L POSTROUTING -n -v

Confirm that the rule appears in the expected chain, has the intended source subnet and egress interface, and shows packet and byte counters increasing while a private client creates a new outbound connection. A rule with zero counters is not necessarily wrong if no matching traffic has occurred, but it tells you that the test flow has not matched it.

Run the test from a host inside the private subnet, not only from the gateway itself. Generate a new connection to the intended external destination, then check:

  • The client uses the Linux server as its gateway.
  • The server’s IPv4 forwarding value is 1.
  • The SNAT or MASQUERADE counter increases.
  • The filter table’s FORWARD policy permits the flow and its replies.
  • The upstream network has a route for the translated address and returns traffic through the translating server.

If the destination sees the wrong source address, inspect the selected egress interface and whether another NAT rule is earlier in the chain. If there is no reply, distinguish a forwarding rejection from a missing return route; both can look like an application timeout from the client.

Troubleshoot the common failure modes

Forwarding is disabled

Symptom: The client cannot reach external networks and NAT counters do not increase. Fix: Check sysctl net.ipv4.ip_forward, set it to 1, and retest with a new connection.

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

The rule is in the wrong table or chain

Symptom: The command exists somewhere in the firewall, but source addresses are unchanged. Fix: Confirm that the rule is in nat, in POSTROUTING, and uses the SNAT target. A filter-table rule cannot perform source translation.

The source or interface match is wrong

Symptom: The rule counter remains at zero. Fix: Compare the client’s actual source address and prefix with -s, and compare the kernel’s selected outgoing interface with -o. Correct either match rather than broadening the rule blindly.

MASQUERADE is used for a stable address

Symptom: The setup works, but the configuration does not clearly express which public address should be used. Fix: For a stable public address, replace MASQUERADE with explicit SNAT and the assigned address. Reserve MASQUERADE for a changing interface address.

The FORWARD policy blocks the packet

Symptom: NAT counters increase, but the client receives no usable response. Fix: Inspect the filter table’s FORWARD chain, its default policy, and the rules for both outbound packets and established replies. Translation and authorization are separate operations.

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

The return route is missing

Symptom: The outbound packet leaves, but replies never reach the client. Fix: Ensure the upstream network routes the translated public address back to this gateway and that the gateway has a valid route toward the private subnet. SNAT cannot compensate for an incorrect upstream route.

The rule disappeared after reboot

Symptom: Connectivity works immediately after entering the command but fails after restart. Fix: Save the rule and forwarding setting through the distribution’s supported persistence mechanism, reload it, and verify the active tables again.

A repeatable configuration checklist

  • Map the private subnet, private interface, egress interface, and translated address.
  • Confirm the translated address is assigned to the server or legitimately usable upstream.
  • Enable net.ipv4.ip_forward=1 and configure it persistently.
  • Use SNAT with --to-source for a stable address.
  • Use MASQUERADE when the egress address changes.
  • Match the internal source subnet and egress interface; add protocol or destination matches only when required.
  • Review and permit the traffic in the filter table’s FORWARD chain.
  • Save the configuration using the host distribution’s supported firewall method.
  • List the active NAT rules with counters.
  • Test a new connection from a private client and verify the return route.

SNAT design decisions at a glance

Decision Use this approach Why it matters
Public address does not change SNAT with --to-source Explicitly selects the stable source address.
Public address changes MASQUERADE Tracks the outgoing interface’s current address.
Only one internal network should be translated Match its source prefix Prevents unrelated traffic from being rewritten.
Only one uplink should be translated Match the egress interface Prevents translation on another route or interface.
Clients still cannot connect Check forwarding, FORWARD policy and return route NAT is only one part of a routed flow.
Rules vanish after restart Use distribution-supported persistence Runtime iptables state is not automatically permanent.

What a correct result looks like

A correct deployment has forwarding enabled, a source-NAT rule in nat/POSTROUTING that matches only the intended private traffic, and a filter policy that allows the forwarded flow and its replies. The NAT rule’s counters rise when a private client opens a new connection. The upstream destination sees the gateway’s stable SNAT address or the current MASQUERADE address, and return traffic follows a route back through the gateway. Finally, the same behavior remains after the host reloads its supported persistent configuration.

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.

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

firewalliptablesLinuxMASQUERADENATnetworkingSNAT

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.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.