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 DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
VGSources
Blog

How to Forward Ports Through a Linux Gateway with iptables

Learn the complete packet path for Linux iptables port forwarding: enable IPv4 routing, DNAT in PREROUTING, allow the translated flow in FORWARD, fix return routes, and persist the rules safely.
Length11 min Posted Quest giverVGSources Team

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.

To forward a port through a Linux gateway, enable IPv4 forwarding, add a destination-NAT (DNAT) rule in the nat table’s PREROUTING chain, and allow the translated connection in the filter table’s FORWARD chain. Replies must travel back through the gateway so conntrack can reverse the translation. Add narrowly scoped source NAT (SNAT or MASQUERADE) only when the internal server’s routing cannot provide that return path.

What port forwarding through a Linux gateway actually does

A gateway forwarding a public TCP port is performing two related jobs. First, destination NAT changes the packet’s public destination address and port to the private server’s address and service port. Second, the filter rules decide whether that translated packet may cross from the WAN interface to the LAN interface.

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.

For an Internet client connecting to public address 203.0.113.10:8443, the normal IPv4 path is:

  1. The packet arrives on the gateway’s WAN interface.
  2. A nat table PREROUTING rule applies DNAT, changing the destination to an internal address such as 192.168.1.20:443.
  3. The kernel routes the packet toward the LAN interface.
  4. The filter table’s FORWARD chain evaluates the translated destination, not the original public destination.
  5. If accepted, the packet reaches the internal host.
  6. The reply must return through the gateway. Conntrack then reverses the NAT mapping before the response leaves for the client.

That order explains the most common mistake: a DNAT rule alone does not authorize forwarding. The FORWARD rule must match the internal address and port because filtering occurs after DNAT. The Linux Packet Filtering HOWTO describes this distinction with the example that the filter sees the “real” destination after translation.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Requirements and information to collect first

  • Root or sudo access on the gateway.
  • A WAN-facing interface name, such as eth0 or ens3, and a LAN-facing interface name, such as eth1 or br0.
  • The internal server’s fixed address, for example 192.168.1.20, and the service’s listening port.
  • The protocol: TCP, UDP, or both. A TCP rule does not forward UDP traffic.
  • A route on the internal host that sends replies back through this gateway, normally by using the gateway’s LAN address as its default route.
  • A decision about whether the distribution uses the iptables-nft compatibility layer or the legacy backend.

Confirm interface names and addresses before writing rules:

ip -br address
ip route
iptables -V

The iptables manual currently identifies version 1.8.13, with an upstream repository state dated 10 July 2026. An output containing nf_tables indicates the nftables-backed implementation; an output containing legacy indicates the older backend. Do not mix assumptions about one backend’s rule set with the other. A rule entered through one implementation may not appear in the other implementation’s listing.

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

Step-by-step: forward a TCP port

1. Make sure the service works internally

From the gateway, test the internal service directly. For HTTPS on port 443, for example:

curl -vk https://192.168.1.20:443/

For a generic TCP listener, use an appropriate client such as nc. If the connection fails directly, port forwarding cannot fix it. Check that the daemon is listening on the expected address, the host firewall permits the connection, and the service is not bound only to loopback.

2. Enable IPv4 forwarding

Enable forwarding immediately for the running kernel:

sudo sysctl -w net.ipv4.ip_forward=1

Verify the Boolean value:

sysctl net.ipv4.ip_forward

The expected output ends with = 1. To make the setting survive a reboot, place the setting in a file under /etc/sysctl.d/, then reload the system configuration:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
echo 'net.ipv4.ip_forward=1' | sudo tee /etc/sysctl.d/99-router.conf
sudo sysctl --system

The exact persistence convention can vary by distribution, but the kernel control itself is net.ipv4.ip_forward.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

3. Add DNAT in PREROUTING

This example forwards public TCP port 8443 to HTTPS on an internal server at 192.168.1.20:443. Replace the interface and address values with yours:

sudo iptables -t nat -A PREROUTING -i WAN_IF -p tcp --dport 8443 
  -j DNAT --to-destination 192.168.1.20:443

-i WAN_IF limits the rule to packets arriving from the Internet-facing interface. The protocol and destination-port match prevent unrelated traffic from being translated. DNAT belongs in the nat table’s PREROUTING chain because the destination must be changed before the routing decision.

4. Permit the translated packet in FORWARD

Allow only the translated destination and service:

sudo iptables -A FORWARD -i WAN_IF -o LAN_IF -p tcp 
  -d 192.168.1.20 --dport 443 
  -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT

The filter sees 192.168.1.20:443, not public port 8443. If your existing policy already accepts new forwarding traffic, do not add a redundant broad rule; retain the narrow rule when you need an explicit exception or an auditable policy.

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

5. Permit replies

Allow replies belonging to an established forwarded connection:

sudo iptables -A FORWARD -i LAN_IF -o WAN_IF -p tcp 
  -s 192.168.1.20 --sport 443 
  -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Many gateways already have one general ESTABLISHED,RELATED rule near the top of FORWARD. If so, that existing rule can cover replies and you should not duplicate it unnecessarily. Keep rule order in mind: an earlier drop rule can prevent these accepts from being reached.

6. Test from outside the LAN

Use a host on the Internet or another network, not just a client inside the same LAN:

nc -vz PUBLIC_ADDRESS 8443

For HTTPS, test the public endpoint with a browser or curl. Testing from inside the LAN may exercise a hairpin-NAT path that requires additional rules and therefore does not prove that ordinary Internet forwarding works.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Forwarding ports 80, 443, 22, and UDP services

The same pattern applies to web servers, SSH, game servers, DNS, VPN endpoints, and other services. The public and private ports may be the same or different.

Use case DNAT destination FORWARD match Security note
HTTP 192.168.1.20:80 -p tcp -d 192.168.1.20 --dport 80 Expose only if the service is intended to be public; prefer HTTPS for credentials.
HTTPS 192.168.1.20:443 -p tcp -d 192.168.1.20 --dport 443 Confirm the certificate and application are configured for the public name.
SSH on a nonstandard public port 192.168.1.20:22 -p tcp -d 192.168.1.20 --dport 22 Restrict the source address or VPN access whenever possible.
UDP service For example, 192.168.1.20:51820 Use -p udp and the internal UDP port UDP has no handshake; verify both directions and application-specific behavior.

For UDP, change both the DNAT and FORWARD rules to -p udp. For example:

sudo iptables -t nat -A PREROUTING -i WAN_IF -p udp --dport 51820 
  -j DNAT --to-destination 192.168.1.20:51820
sudo iptables -A FORWARD -i WAN_IF -o LAN_IF -p udp 
  -d 192.168.1.20 --dport 51820 
  -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i LAN_IF -o WAN_IF -p udp 
  -s 192.168.1.20 --sport 51820 
  -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Some UDP protocols create related flows, while others send replies that conntrack classifies differently. Inspect the service’s documented port requirements rather than assuming one port is sufficient.

When to use SNAT or MASQUERADE

DNAT changes the destination, but it does not automatically fix an incorrect return route. If the internal server’s default gateway is this Linux gateway, the reply normally comes back through it and conntrack can undo the translation. If the server sends replies to another router, the client may see a timeout even though the forwarded packet reached the server.

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.

The preferred fix is usually to correct the internal host’s default route or add an appropriate route for the client networks. Source NAT is a workaround when changing the server’s routing is impossible. It makes the server see the gateway as the source, guaranteeing a symmetric return path but hiding the original client address from the server.

For a narrowly scoped TCP forwarding rule, MASQUERADE can be applied in POSTROUTING on the LAN interface:

sudo iptables -t nat -A POSTROUTING -o LAN_IF -p tcp 
  -d 192.168.1.20 --dport 443 -j MASQUERADE

Use a matching UDP rule for UDP services. Restrict the rule by output interface, protocol, internal destination, and destination port. Avoid a blanket MASQUERADE rule that rewrites every packet crossing the gateway unless that broad behavior is an intentional part of the router design. MASQUERADE is a form of source NAT in POSTROUTING; DNAT is destination NAT in PREROUTING.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Hairpin NAT for clients inside the LAN

A LAN client that accesses the gateway’s public address follows a different path from an Internet client. The DNAT rule may translate the destination, but the internal server can reply directly to the LAN client instead of through the gateway. That asymmetric path breaks the connection-tracking expectation.

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

Test hairpin access separately. If it is required, add a LAN-side DNAT match for the public address and a narrowly scoped LAN-side MASQUERADE rule so the server returns through the gateway:

sudo iptables -t nat -A PREROUTING -i LAN_IF -p tcp 
  -d PUBLIC_ADDRESS --dport 8443 
  -j DNAT --to-destination 192.168.1.20:443
sudo iptables -t nat -A POSTROUTING -o LAN_IF -p tcp 
  -d 192.168.1.20 --dport 443 -j MASQUERADE

Use the actual public address assigned to the gateway and add corresponding FORWARD permissions if the filter policy requires them. Hairpin rules should not be added merely because Internet forwarding works; they solve a separate, LAN-to-LAN test path.

Persistence, rollback, and backend choice

Rules added with iptables -A are normally runtime state and can disappear at reboot or after a firewall-management service reloads them. Save the complete ruleset using the persistence mechanism supported by your distribution. A generic export is:

sudo iptables-save | sudo tee /path/to/your/rules.v4

The file path and restore service are distribution-specific. Some systems load a rules file through an iptables service; others expect nftables-native configuration or a firewall manager. Do not assume that creating a file is enough. Document whether the active backend is nftables-backed or legacy, which service restores it, and how to roll back a change.

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

Before editing a production gateway, export the current rules and record counters:

sudo iptables-save > firewall-backup.v4
sudo iptables -t nat -L PREROUTING -n -v
sudo iptables -L FORWARD -n -v

The nftables-backed iptables command and legacy iptables command can maintain separate rule sets. If a rule appears to have no effect, confirm that the command used to inspect rules is using the same backend as the command used to add them. Distributions that prefer nftables-native syntax may provide clearer long-term management through nftables, but the packet path—DNAT before routing, filtering after translation, and a symmetric return path—remains the same.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting a timeout or failed connection

The service is not reachable directly

Start at the internal host. From the gateway, connect to the private address and port. Check the daemon’s listening sockets and the host’s own firewall. A forwarding rule cannot make a stopped service listen.

IPv4 forwarding is disabled

Run:

sysctl net.ipv4.ip_forward

If the value is 0, enable it and then fix persistence as described earlier. A correct DNAT rule with forwarding disabled will still fail.

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

DNAT counters remain at zero

Inspect the rule and its counters:

sudo iptables -t nat -L PREROUTING -n -v

Zero packets usually means the traffic is arriving on a different interface, uses a different protocol or public port, reaches another gateway, or is being tested from a path that never enters WAN-side PREROUTING. Check the public address and use a packet capture on the expected WAN interface.

DNAT increments but FORWARD drops the packet

Inspect the filter chain:

sudo iptables -L FORWARD -n -v

Match the internal address and internal port in the accept rule. Remember that the filter sees 192.168.1.20:443, not PUBLIC_ADDRESS:8443. Check rule order and the chain’s default policy; an earlier reject or drop can win.

The packet reaches the server but no reply returns

Capture both sides of the gateway:

sudo tcpdump -ni WAN_IF tcp port 8443
sudo tcpdump -ni LAN_IF host 192.168.1.20 and tcp port 443

If the SYN appears on the LAN capture but no response leaves the server, inspect the service, host firewall, and server route. If a response leaves the LAN interface but never appears on the WAN capture, inspect the gateway’s FORWARD return rule, routing, reverse-path filtering, and any source-NAT rule. The internal host’s default route is the most important return-path check.

Only LAN clients fail

Test from an external network. If external access succeeds, the forwarding configuration is likely correct and the missing piece is hairpin NAT or split DNS. Treat the LAN-to-public-address path as a separate design requirement.

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

Rules disappear after reboot

Verify the saved rules file, the restore service, and the backend selected at boot. A firewall manager may overwrite manually entered rules. Export the active ruleset after every intentional change and test restoration during a maintenance window.

Security practices for exposed ports

  • Match the ingress interface, protocol, public port, internal address, and internal port in every DNAT rule.
  • Permit only the required flow in FORWARD; avoid broad any-to-any forwarding.
  • Use conntrack states so new inbound connections and return traffic have separate, reviewable rules.
  • Restrict administrative services such as SSH to known source networks or a VPN whenever possible.
  • Keep the internal service and operating system patched, and expose only a service that is designed to accept untrusted traffic.
  • Review packet and byte counters periodically. Unexpected growth can reveal scans, misrouting, or an overly broad match.
  • Back up the rules before changes and retain a tested rollback procedure.

IPv6 and dual-stack gateways

net.ipv4.ip_forward controls IPv4 only. IPv6 traffic uses separate kernel forwarding controls and ip6tables or nftables rules. Do not assume an IPv4 DNAT rule forwards IPv6, and do not publish an IPv6 service merely because its IPv4 counterpart is protected. Decide explicitly whether the service should be reachable over each address family and build and test the corresponding filter policy.

Choosing between iptables backends and nftables-native rules

Consideration iptables-nft compatibility layer iptables-legacy nftables-native configuration
Command style Traditional iptables commands translated to nftables rules Traditional iptables kernel interface and rule format Native nft syntax and tables/chains
IPv4 and IPv6 Use separate iptables and ip6tables command families Use separate iptables and ip6tables command families Can model both families in one ruleset design
Stateful filtering Conntrack matches remain available Conntrack matches remain available Conntrack is expressed with nftables syntax
Persistence Depends on the distribution’s restore service Depends on the distribution’s restore service Usually managed by the distribution’s nftables service
Visibility Inspect with matching iptables commands and, where appropriate, nft tools Inspect with legacy iptables commands Inspect the native nftables ruleset and counters

The practical choice is the backend your distribution actively manages. Whichever syntax you use, keep the same least-privilege matches, verify counters, and test a saved restore procedure.

Final operational checklist

  • The service answers on the internal address when tested from the gateway.
  • sysctl net.ipv4.ip_forward reports 1.
  • DNAT is in nat/PREROUTING and matches the correct WAN interface, protocol, and public port.
  • FORWARD accepts the translated internal destination and service port.
  • Established and related replies are allowed back toward the WAN.
  • The internal server’s route returns through the gateway, or a narrowly scoped MASQUERADE rule compensates for a route that cannot be changed.
  • External and, if needed, hairpin tests have been run separately.
  • The active backend is documented, counters have been checked, and the rules persist through reboot or firewall-service reload.

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.

Leave a Reply

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

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.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver 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.