Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Write iptables Block Rules and Save Them in rules.v4

A practical guide to writing narrowly scoped iptables DROP rules, protecting SSH and established traffic, saving a complete rules.v4 file, and verifying persistence after reboot.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To block an address or service with iptables and keep the rule after a reboot, add a narrowly scoped DROP rule to the correct chain, test the whole ruleset, save the working IPv4 configuration as /etc/iptables/rules.v4, and make sure a startup service restores it. The order matters: an earlier ACCEPT can prevent a later block from matching, while an overly broad drop can cut off SSH or another management path.

What rules.v4 is responsible for

iptables rules loaded at runtime live in the kernel’s netfilter tables. They are not automatically permanent. Debian documentation puts the consequence plainly: “As IP-Tables are not persistent, they will be deleted ("flushed") with the next reboot.” The file /etc/iptables/rules.v4 is a saved, declarative IPv4 ruleset; it does nothing by itself until a restore command or a persistence service loads it.

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.

A practical workflow therefore has two separate parts:

  • Runtime change: append or insert a rule, then inspect and test the active rules.
  • Persistence: save the known-good active rules to rules.v4 and arrange for them to be restored during startup.

The file should represent the complete filter-table configuration you intend to run, not just an isolated line copied from a command prompt. Saving the complete active ruleset preserves chain definitions, ordering, counters, and other rules that your host already needs.

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

Check the host before changing anything

Inspect current rules and line order

Start with a read-only inspection:

sudo iptables -L -v --line-numbers
sudo iptables-save

The first command shows the filter chains, packet and byte counters, targets, and rule numbers. The second prints a restorable representation of the active tables. Read both before editing so you know whether SSH, loopback traffic, established connections, or application ports are already allowed.

Identify the iptables backend

Some systems run the traditional legacy iptables implementation; others provide iptables commands through an iptables-nft compatibility layer. Debian has used nftables as its default firewall framework since Debian 10 (Buster), so the command name alone does not prove which backend is active. Check the alternatives and the installed command on the host, and keep the backend consistent when inspecting, saving, and restoring rules. A ruleset created through one implementation should not be assumed to behave identically when loaded through another.

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

Confirm that you have a recovery path

Firewall mistakes are especially risky over a remote session. Before applying a broad change, keep a second management session open, record the current output of iptables-save, and know how you will restore it. A test machine or console access is preferable when you are changing SSH or the default policy.

Choose the right chain and write a narrow block

iptables evaluates packets in chains. Select the chain based on where the traffic is observed:

Chain Use it for Example direction
INPUT Traffic destined for this host An unwanted client connecting to a local service
OUTPUT Traffic generated by this host Preventing the host from contacting a particular address
FORWARD Traffic routed through this host Blocking a connection between two forwarded networks

DROP discards a matching packet without permitting it to continue. Use the smallest match that answers the actual requirement.

Block one source address on inbound traffic

sudo iptables -A INPUT -s 203.0.113.10 -j DROP

This appends a rule that drops packets entering the host from the example IPv4 address. Replace the address with the one you have verified. Appending is easy to understand, but it is only correct if earlier rules do not already accept that traffic.

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

Block a TCP destination port

sudo iptables -A INPUT -p tcp --dport 25 -j DROP

This blocks new inbound TCP packets addressed to port 25. It does not block UDP traffic on the same number, traffic in another chain, or packets that an earlier rule has already accepted. If the service uses a different protocol or port, match that protocol and port explicitly.

Prevent outbound connections to an address

sudo iptables -A OUTPUT -d 203.0.113.10 -j DROP

This applies to traffic leaving the host for the example destination. It is different from an inbound block: a host can still receive traffic from that address unless an INPUT rule also matches it.

Put safety rules before a general drop

Rule order is decisive. iptables evaluates a chain from the top. When a packet matches a terminating target such as ACCEPT or DROP, later rules in that chain are not consulted for that packet.

Most hosts need at least these considerations before a broad block:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Allow loopback traffic on lo so local services can communicate.
  • Allow ESTABLISHED,RELATED traffic so replies to connections you already permitted are not discarded.
  • Allow SSH or another management service before any general inbound drop, with a source restriction where appropriate.
  • Keep required service-port rules ahead of a catch-all policy.

A narrow block can safely appear after the specific accepts it must not override. Conversely, placing a blanket DROP at the top can lock out administration before the SSH accept is reached. Do not copy a sample policy wholesale: the right baseline depends on the services and routing role of your host.

Example complete filter-table file

The following is a minimal structure illustrating ordering. It allows loopback, permits established and related traffic, allows TCP port 22, and then drops the example source. Adapt it to the host rather than treating it as a universal policy.

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
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p tcp --dport 22 -j ACCEPT
-A INPUT -s 203.0.113.10 -j DROP
COMMIT

The *filter header selects the filter table, the colon lines define built-in chain policies and counters, each -A line adds a rule in order, and COMMIT ends the transaction. A complete file may contain additional tables or custom chains; preserve those when saving an existing configuration.

Apply and test a ruleset safely

Testing a command-line change

When you add a rule directly, inspect the result immediately:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo iptables -A INPUT -s 203.0.113.10 -j DROP
sudo iptables -L INPUT -v --line-numbers

Check that the rule appears in the intended position, has the expected source, protocol, port, and target, and that counters change when matching traffic arrives. Counters are evidence that the rule is seeing packets; zero counters may simply mean no matching traffic has occurred yet.

Testing a prepared file

To load a file as a complete ruleset, use:

sudo iptables-restore < /etc/iptables/rules.v4

From a remote session, keep the second management connection available while testing. If the file contains an ordering error or omits an access rule, the spare session gives you a chance to restore the previous configuration. Test both the traffic you intend to block and the traffic that must remain available, such as an existing SSH connection and required application flows.

Validate the complete active configuration

After a restore, run:

sudo iptables -L -v --line-numbers
sudo iptables-save

Compare the active output with the file you intended to load. Confirm chain policies, rule order, targets, and counters. A single successful test of the blocked address is not enough if the same host must also accept management, DNS, monitoring, or application traffic.

Save the known-good rules to /etc/iptables/rules.v4

Once the active ruleset has passed your checks, save exactly what is loaded:

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.
sudo iptables-save | sudo tee /etc/iptables/rules.v4

tee performs the file write with elevated privileges. An equivalent root-owned redirection is:

sudo sh -c 'iptables-save > /etc/iptables/rules.v4'

Use one method, then inspect the file:

sudo sed -n '1,200p' /etc/iptables/rules.v4

The file should contain a complete, syntactically valid dump, including table headers, chain declarations, rules in their evaluation order, and COMMIT lines. If the directory does not exist on a minimal installation, create it with appropriate root ownership before saving. Restrict write access because this file controls the host firewall.

Do not edit the file and assume the running firewall changed. File edits take effect only after a restore. Conversely, a runtime rule that was never saved disappears at the next reboot or when another configuration manager flushes the table.

Enable loading at startup

Use the netfilter-persistent integration

On Debian systems, the persistence package integrates startup loading with the saved files. Its manual defines these operations:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • start loads persistent rules.
  • stop stops the service action.
  • flush removes the currently loaded rules through the plugins.
  • save asks plugins to save the currently loaded rules to persistent storage.

With the package installed, the relevant commands are:

sudo netfilter-persistent save
sudo netfilter-persistent start

save records the rules currently loaded, while start loads them. The package’s startup integration is what makes the file effective after a reboot. Debian’s package template also documents saving current IPv4 rules to /etc/iptables/rules.v4 and loading them automatically during startup; it points to iptables-save(8) for ongoing updates.

Check that the persistence package is actually present

If netfilter-persistent is not found, install the distribution package that supplies it, then save the known-good rules and enable its normal startup integration. Package names and service-management details can vary with the distribution release, so confirm the installed unit and its status on the host rather than assuming a command intended for another release.

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

Verify after reload and reboot

First perform a manual reload:

sudo iptables-restore < /etc/iptables/rules.v4
sudo iptables -L -v --line-numbers

This catches syntax and ordering problems without waiting for a restart. Then reboot during a maintenance window and verify the same items after the system returns:

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.
  • The expected chains and default policies exist.
  • The block rule appears in the intended position.
  • SSH and other required management paths still work.
  • Allowed services are reachable from their permitted sources.
  • Matching traffic increments the expected counters.

If the rules vanish after reboot, inspect whether the persistence package is installed and enabled, whether the file is at the exact path /etc/iptables/rules.v4, and whether the startup service is using the same iptables backend you used to create the file.

Choosing between common approaches

Approach Strength Risk or limitation Best use
Immediate command-line rule Fast feedback and easy to test Lost on reboot unless saved Interactive testing or an urgent, narrowly scoped change
Declarative rules.v4 file Records a complete ordered IPv4 configuration Editing without a restore does not change the running firewall Reviewable, repeatable configuration
Manual iptables-restore Loads a known file on demand Someone must run it after each reboot or change Controlled testing, recovery, and maintenance
Boot-time netfilter-persistent loading Restores saved rules automatically Depends on package, startup integration, and backend consistency Hosts that must retain IPv4 filtering across restarts
Legacy iptables implementation Uses the traditional command semantics May differ from the host’s nftables-backed tooling Systems intentionally standardized on legacy netfilter tools
iptables-nft compatibility layer Allows familiar iptables commands on nftables-based systems Backend differences can surprise scripts and mixed configurations Debian installations using the current default framework
Narrow match-specific DROP Limits collateral impact Requires accurate source, protocol, port, and chain selection Blocking one address, service, or direction
Broad chain policy or catch-all drop Strong default-deny posture Can block administration and legitimate services if ordered incorrectly Deliberately designed policies with documented allow rules first

Troubleshooting common failures

The rule is present but traffic still passes

  • Inspect line numbers and look for an earlier ACCEPT that matches the packet.
  • Confirm the packet enters the chain you changed: local destinations use INPUT, locally generated traffic uses OUTPUT, and routed traffic uses FORWARD.
  • Check protocol and port matches. A TCP rule does not match UDP, and a destination-port match does not match every direction.
  • Use verbose counters to determine whether packets reach the rule at all.

SSH stopped working after a change

Use the second session or console access to inspect the order. Move the intended management accept ahead of the broad drop, restore the last known-good dump, and test again before saving. Do not repeatedly append exceptions without checking whether an earlier terminating rule still prevents them from being reached.

The rule worked until reboot

Runtime changes are not persistence. Save the active rules with iptables-save, verify that /etc/iptables/rules.v4 contains them, and confirm that the netfilter-persistent startup integration is installed and enabled. A manual restore proves the file is usable; a reboot test proves the startup path is functioning.

The restore command reports an error

Check that the file has complete table syntax, valid chain declarations, correctly ordered rules, and a terminating COMMIT. Ensure you are restoring an IPv4 file with the host’s installed iptables implementation. If the system uses an nftables-backed compatibility layer, investigate backend selection before mixing files or commands from a legacy installation.

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

Saving overwrote rules you still needed

iptables-save captures the rules currently loaded, so an accidental flush or partial test can be saved just as easily as a correct configuration. Keep a dated backup of the previous file and retain the pre-change output. Save only after validating management access and required service traffic.

Scope and IPv6 considerations

/etc/iptables/rules.v4 is the conventional persistence file for IPv4 rules. If the host also handles IPv6, manage and persist its IPv6 rules separately using the system’s supported mechanism; an IPv4 drop does not automatically block an IPv6 connection to the same service. Test both address families when the service is reachable over both.

A repeatable checklist

  1. Run sudo iptables -L -v --line-numbers and sudo iptables-save; identify the backend and record the current configuration.
  2. Decide whether the traffic belongs in INPUT, OUTPUT, or FORWARD.
  3. Write the narrowest appropriate DROP match for the verified address, protocol, port, and direction.
  4. Check that loopback, established and related traffic, SSH, and required services are accepted before any broad drop.
  5. Apply the rule or restore a prepared file while retaining a recovery session.
  6. Inspect order, targets, and counters; test blocked and permitted traffic.
  7. Save the known-good active rules with sudo iptables-save | sudo tee /etc/iptables/rules.v4.
  8. Run sudo netfilter-persistent save and verify the startup integration.
  9. Manually restore the file, inspect the result, then verify again after a planned reboot.

The Bottom Line

A persistent iptables block is a combination of correct matching and reliable loading: place the specific DROP in the right chain and position, validate the complete active ruleset, save it to /etc/iptables/rules.v4, and verify that netfilter-persistent restores the same file at startup.

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 *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
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.