Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween 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 Scan×
Skip to content
World desk10 min

How to Block Traffic by Country on a Linux VPS

Country blocking on a Linux VPS requires current IPv4 and IPv6 address maps. This guide shows safe nftables and firewalld implementations, testing, logging, updates and recovery.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use country-to-IP-range data, not a country field in each packet. Generate current IPv4 and IPv6 maps, load them into nftables (or into firewalld IP sets), and drop packets whose source address maps to a selected country. Keep an out-of-band console available, allow your own management addresses first, test on one service, and retain a rollback ruleset.

This is classification by address allocation. It is useful for reducing unwanted exposure, but it is not an identity or location guarantee: VPNs, proxies, mobile networks, cloud hosts and stale allocation data can make a connection appear to come from another country.

As an Amazon Associate I earn from qualifying purchases.

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.

What country blocking can and cannot do

A firewall sees source and destination addresses, ports, protocols and connection state. It does not receive a trustworthy country attribute from the Internet. Geo-blocking therefore means looking up the source address in a database of country-assigned ranges and applying the result to the packet.

The database normally arrives as two datasets: one describing country codes and one mapping address ranges to those codes. IPv4 and IPv6 require separate maps. If you build only an IPv4 list, IPv6 clients can bypass the policy whenever your VPS advertises an IPv6 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.
  • Good use: reducing opportunistic scans or limiting a service to a known geography when occasional false positives are acceptable.
  • Poor use: enforcing legal identity, preventing determined users from connecting, or treating a country code as proof of a person’s location.
  • Operational requirement: refresh the underlying ranges. Allocations change, and the source documentation does not prescribe one universal refresh interval.

Decide the scope before writing rules. Blocking every service is a very different change from blocking only an administrative port or a public web listener. A narrow first deployment is easier to verify and undo.

Choose nftables, firewalld or legacy iptables

Approach Best fit IPv4 and IPv6 Persistence and updates Main caution
Raw nftables A host where you control the complete ruleset and want direct map lookups. Use the separately generated IPv4 and IPv6 maps. You include generated files in your ruleset and reload them when the data is regenerated. Rule order, syntax and rollback are entirely your responsibility.
firewalld A distribution that already uses firewalld zones, IP sets and rich rules. Create sets and rules for both address families. Runtime and permanent configuration are separate; test at runtime, then save permanently. Mixing direct rules with an nftables-backed firewalld ruleset can produce surprising acceptance behavior.
iptables Only when an existing, deliberately maintained legacy ruleset requires it. Separate IPv4 and IPv6 tooling and generated CIDR rules are needed. Large generated rule lists are cumbersome to refresh and persist. firewalld documents the iptables backend as deprecated and says it will be removed in a future release.

On firewalld systems, the documented configuration values are nftables (the default) or iptables. Prefer the native nftables path for new work unless a distribution or application requirement says otherwise. Rich rules should be preferred over direct rules when they express the policy you need.

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

Prepare a safe rollout

  1. Verify out-of-band access. Log in to your VPS provider’s serial, web or rescue console and confirm that it works before changing the firewall. A country rule can lock out SSH as effectively as a typo.
  2. Record the current state. Save the active nftables ruleset or firewalld configuration, note the public IPv4 and IPv6 addresses you use for administration, and write down how to restore the previous state from the console.
  3. Define an allow-list. Permit your administrator addresses or trusted management network before the country drop. If your address is dynamic, use a controlled management network or provider console rather than assuming today’s address will remain valid.
  4. Choose a test service. Apply the first rule to one port or one dedicated test host. Do not begin with an all-services drop on a production VPS.
  5. Plan connection behavior. If your rules accept established connections before the country drop, an already-open session may continue. That is often safer during rollout, but it is not an immediate block. Put the country drop earlier only when you have a verified recovery path.

Build GeoIP maps for nftables

The nftables GeoIP workflow documented for Linux uses a generator commonly named nft_geoip.py. It consumes a country/location CSV and an address-range CSV, then produces country definitions plus separate geoip-ipv4.nft and geoip-ipv6.nft map files. Obtain the generator and the two current CSV inputs from the source you have selected, and follow that version’s built-in usage help: option names and input-column expectations can differ between releases.

Generate and install the files

  1. Download or otherwise retrieve the current location and address CSV files over a trusted channel.
  2. Run the generator with those files and inspect its output. Confirm that it created the country-definition file and both address-family map files; an IPv4-only result is incomplete.
  3. Store the generated files under a root-owned directory used by your firewall configuration, with permissions that prevent unprivileged modification.
  4. Keep the previous generated set until the new rules have loaded successfully. A bad download or malformed CSV should be a failed deployment, not an empty allow-all firewall.

The generated map values are country marks. The documented examples set a packet mark from the source address with meta mark set ip saddr map @geoip4 for IPv4 and meta mark set ip6 saddr map @geoip6 for IPv6. The actual map names and definition names come from the files produced by your generator, so use those names rather than copying names from an unrelated version.

Illustrative nftables policy

The following is a policy shape, not a drop-in universal file. Adjust the include paths, generated map names, country-code definitions and chain priority to your distribution, then validate it before loading:

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.
table inet country_filter {
    chain input {
        type filter hook input priority filter;
        policy accept;

        # Keep trusted administration ahead of the country drop.
        ip saddr { 198.51.100.10 } accept
        ip6 saddr { 2001:db8:1234::10 } accept

        # Generated map lookups; names must match your generated files.
        meta mark set ip saddr map @geoip4
        meta mark set ip6 saddr map @geoip6

        # Replace BLOCKED_COUNTRY with the mark defined by your generator.
        meta mark BLOCKED_COUNTRY counter log prefix "geoip-country-drop " drop
    }
}

The address examples above use documentation-reserved networks and are not real administrator addresses. Replace them with the addresses you intend to trust. Include the generated definition and map files in the actual ruleset before this chain; the exact include filenames are determined by your generator.

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

Many administrators place established/related acceptance and essential loopback or ICMP handling before classification. That preserves existing sessions and basic host operation, but it also means a session already classified as established may not be cut off by a later country rule. Decide deliberately which behavior you need.

Validate before committing

  1. Ask nftables to parse the complete ruleset in a non-destructive validation mode supported by your distribution.
  2. Load the candidate ruleset while an SSH session remains open and keep the provider console ready.
  3. From a permitted management address, verify SSH and any required control-plane service. From a controlled test network, verify that the selected test port is dropped.
  4. Inspect the chain and its counters. A rule that never increments may indicate that traffic is arriving over the other address family, matching an earlier accept, or using a different interface or service than expected.
  5. Only after verification, save the ruleset through your distribution’s normal persistence mechanism.

Implement the same policy with firewalld

firewalld wraps the underlying firewall with zones, source matching, IP sets, rich rules and separate runtime and permanent configuration. Its command-line manual defines a source as an address, network, MAC address or an IP set referenced with the ipset: prefix.

Create IPv4 and IPv6 sets

Use two sets when you need unambiguous family handling. The exact set type and family options depend on the firewalld version, but the pattern is:

firewall-cmd --new-ipset=country_block_v4 --type=hash:net --family=inet
firewall-cmd --new-ipset=country_block_v6 --type=hash:net --family=inet6

Run these first without --permanent as a runtime test. Add every generated network for the selected country to the matching set:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy 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
firewall-cmd --ipset=country_block_v4 --add-entry=203.0.113.0/24
firewall-cmd --ipset=country_block_v6 --add-entry=2001:db8:abcd::/48

The networks above are documentation examples, not country allocations. Populate the sets from your generated address CSV; do not infer a country from these sample ranges.

Attach the sets to a zone

You can attach a set as a zone source or express a drop as a rich rule. A source-based zone example is:

firewall-cmd --zone=public --add-source=ipset:country_block_v4
firewall-cmd --zone=public --add-source=ipset:country_block_v6

If the zone’s target and services would not produce the exact behavior you want, use rich rules instead:

firewall-cmd --zone=public --add-rich-rule='rule source ipset=country_block_v4 drop'
firewall-cmd --zone=public --add-rich-rule='rule source ipset=country_block_v6 drop'

Check the syntax accepted by your installed firewalld release, list the resulting zone and IP-set configuration, and test while the changes are runtime-only. Once verified, repeat the successful changes with --permanent or create the permanent objects directly, then run firewall-cmd --reload. A reload replaces runtime state with the saved permanent configuration, so confirm that your administrator allow-list and both sets exist in the permanent view before reloading.

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

Understand direct-rule precedence

The firewalld documentation recommends rich rules when they can express the requirement. With FirewallBackend=nftables, a direct-rule ACCEPT does not necessarily accept a packet immediately; the packet can still be evaluated by firewalld’s nftables ruleset. A direct-rule DROP, however, is dropped immediately regardless of backend. This asymmetry is a reason to avoid mixing independently managed direct iptables-style rules with zone and rich-rule policy unless you have traced the resulting ruleset and documented the order.

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why legacy iptables is usually the wrong starting point

iptables does not provide a built-in, authoritative country database. A country policy requires converting every selected-country range into individual IPv4 and IPv6 rules, then arranging those rules ahead of the services they should block. Large lists make reloads slower, persistence more fragile and review more difficult than a map lookup.

Some systems still run an iptables-compatible command while firewalld programs nftables underneath. The command name alone does not tell you which backend is active. Check the firewalld backend and the actual ruleset before adding rules. Because the iptables backend is documented as deprecated and scheduled for removal in a future release, treat it as a compatibility constraint rather than a new design.

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.

Logging, counters and troubleshooting

No packets are being blocked

  • Check both families. A client may be reaching the VPS over IPv6 while you populated only an IPv4 set.
  • Confirm that the address maps were included and that their names match the rules.
  • Inspect counters on the country rule and on earlier accepts. Earlier rules, zone targets or an established-session rule may be handling the packet first.
  • Verify that the test source really belongs to the selected country in the data version you installed. VPN and cloud egress addresses often differ from a user’s physical location.

Legitimate administrators are locked out

  1. Use the provider’s out-of-band console, not repeated SSH guesses.
  2. Remove or disable the country drop, or restore the saved previous ruleset.
  3. Add the correct IPv4 and IPv6 management addresses ahead of classification.
  4. Test a second session before closing the console session.

The rule matches too much or too little

Country data is an allocation mapping, not a real-time geolocation service. Recheck the CSV version, range boundaries and address family. Also check whether a reverse proxy, load balancer or CDN is the source seen by the VPS; in that architecture, the firewall may see the proxy’s address rather than the visitor’s address.

Use observability without flooding logs

Add a counter to each country drop and enable rule-level logging only at a rate your host can handle. nftables documentation describes rule logging and notes that full logging support begins with Linux kernel 3.17. Use a distinctive prefix, review system logs, and remove or rate-limit verbose logging after validation. Counters are often sufficient for ongoing confirmation and create less noise.

Keeping country data current

Address ownership changes, and the generator’s output is only as current as the CSV files you feed it. Establish a repeatable refresh job even though no universal interval is prescribed. A safe refresh sequence is:

  1. Fetch the new location and address files and verify their integrity.
  2. Generate a new, versioned IPv4 map, IPv6 map and country-definition file in a staging directory.
  3. Validate syntax and confirm that both families contain entries.
  4. Load the candidate ruleset or update firewalld’s runtime IP sets while maintaining console access.
  5. Test allow-listed administration and the blocked service, inspect counters, then make the change permanent.
  6. Retain the previous data set for immediate rollback and record the data version and deployment time.

Do not silently replace a working map with an empty file after a failed download. Make the update fail closed for the deployment process itself: keep the last known-good files in place and alert an administrator.

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

Decide whether a country block belongs on the VPS

Use host-level geo-blocking when the VPS is the right enforcement point and you can maintain the data and rollback path. If traffic passes through a provider firewall, load balancer or reverse proxy, enforcing the policy there may reduce host load and give you a clearer client address. Conversely, a host rule remains useful as defense in depth when upstream controls are unavailable.

For most new Linux VPS deployments, raw nftables maps are the most direct implementation. Choose firewalld when it already owns the host policy and you want zones, IP sets and permanent configuration. Keep legacy iptables only for a documented compatibility need, and do not mix backends casually.

Frequently Asked Questions

Will country blocking stop VPN users?

No. The firewall classifies the source address it receives. A VPN, proxy, mobile carrier or cloud egress point can make the connection appear to originate in another country.

Do I need separate IPv4 and IPv6 rules?

Yes. Complete coverage requires the separately generated IPv4 and IPv6 maps and corresponding rules or firewalld IP sets.

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

Can I block only SSH instead of every service?

Yes. Apply the country match in the SSH-specific rule or service scope first, then expand only after testing. Keep a provider console and an administrator allow-list available.

How often should GeoIP maps be refreshed?

There is no universal interval in the documented workflow. Set a schedule appropriate to your risk, regenerate from current CSV data, validate both families, and retain the previous working maps for rollback.

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.

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.