
GeoIP is one of those technologies that quietly sits in the background of many systems, yet it can be extremely powerful when used correctly. Whether you want to block traffic from specific countries, analyze access logs, or add geographic context to security events, GeoIP can be a valuable addition to your Linux toolbox.
In this article, we’ll go deeper and look at real GeoIP usage examples for:
- Log analysis
- Firewalls
- Apache HTTP Server
- HAProxy
All examples are based on typical GNU/Linux server environments.
What Is GeoIP?
GeoIP maps an IP address to geographic data such as:
- Country
- City
- ASN / ISP (depending on database)
Most modern systems use MaxMind GeoLite2 databases (
.mmdb
format).
Keep in Mind ! :
GeoIP data is approximate. VPNs, proxies, mobile networks, and CGNAT reduce accuracy. GeoIP should be treated as a heuristic, not a guarantee.
1. Installing GeoIP Databases on Linux deb based distro
On Debian / Ubuntu:
#
apt install geoipupdate
Configure
/etc/GeoIP.conf
with your MaxMind license key and run:
# geoipupdate
Databases are usually stored in:
/usr/share/GeoIP/
2. GeoIP for Log Analysis (to get idea of where does your traffic origins from)
GeoIP with Apache HTTP Server
Apache can use GeoIP in two main ways:
-
To do IP origin Logging
-
Do Access control based on IP origin
An altenartive GeoIP common use is to post-processing logs to find out attempts to breach your security.
Lets say you want to
Find top attacking countries against your SSHd service.
# grep "Failed password" /var/log/auth.log | \
awk '{print $(NF-3)}' | \
while read ip; do geoiplookup $ip; done |
\ sort | uniq -c | sort -nr
This command will provide you a visibility on attack sources georaphical Country origin
3. Installing Apache GeoIP Module
For legacy GeoIP (older systems):
# apt install libapache2-mod-geoip
For modern systems, GeoIP2 is preferred:
# apt install libapache2-mod-geoip2
Enable the module:
# a2enmod geoip2
# systemctl reload apache2
4. Configure GeoIP Logging in Apache (basic config)
Add country code to access logs:
LogFormat "%h %l %u %t \"%r\" %>s %b %{GEOIP_COUNTRY_CODE}e" geoip
CustomLog /var/log/apache2/access.log geoip
This allows you to analyze traffic by country later without blocking users.
5. Country-Based Filter Blocking in Apache based on IP origin
Example: allow only selected countries:
<IfModule mod_geoip2.c>
SetEnvIf GEOIP_COUNTRY_CODE ^(BG|DE)$ AllowCountry
Deny from all
Allow from env=AllowCountry
</IfModule>
Use this carefully. Blocking at the web server layer is better than firewall-level blocking, but still risky if you have global users.
6. Apply GeoIP to Apache Virtual Host
You can apply GeoIP rules per site:
<VirtualHost *:80>
ServerName example.com
<IfModule mod_geoip2.c>
SetEnvIf GEOIP_COUNTRY_CODE CN BlockCountry >
Deny from env=BlockCountry
</IfModule>
</VirtualHost>
This is useful when only specific applications need filtering.
Firewall vs Application Layer GeoIP (Pros and Cons)
| Layer | Pros | Cons |
|---|---|---|
| Firewall | Early blocking | Hard to debug |
| Apache | Flexible per-site rules | App overhead |
| HAProxy | Centralized control | Requires careful config |
| Logs only | Safest | No blocking |
7. Apply GeoIP to HAProxy
HAProxy is an excellent place to apply GeoIP logic because:
- It sits in front of applications
- Rules are fast and explicit
- Logging is centralized
a. Preparing GeoIP Filtering to HAProxy service
HAProxy supports GeoIP2 via Lua or native ACLs using
.mmdb
Example directory:
/usr/share/GeoIP/GeoLite2-Country.mmdb
b. GeoIP-Based Access Control Lists ( ACLs ) in HAProxy
Basic country-based blocking:
frontend http_in
bind *:80acl from_china src -m geoip CN
acl from_russia src -m geoip RUhttp-request deny if from_china
http-request deny if from_russiadefault_backend web_servers
This blocks traffic early, before it hits Apache or nginx.
c. GeoIP-Based Routing across different haproxy backends
Instead of blocking, you can route traffic differently:
acl eu_users src -m geoip DE FR NL
use_backend eu_backend if eu_users
default_backend global_backend
This is useful for:
- Geo-based load balancing
- Regional content
- Legal compliance separation
d. GeoIP Logging config for HAProxy
Add country code to logs:
log-format "%ci:%cp [%t] %ft %b %s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %CC"
(%CC = country code)
This makes traffic analysis extremely efficient.
Keep in Mind !
Use HAProxy or web server level for enforcement, and firewall GeoIP only when absolutely necessary.
8. Fail2ban + GeoIP: Smarter Bans, Better Context
Fail2ban is excellent at reacting to abusive behavior, but by default it only sees IP addresses, not where they come from. Adding GeoIP allows you to:
- Tag bans with country information
- Apply different ban policies per region
- Detect unusual behavior patterns
a. GeoIP-Enriched Fail2ban Logs
Fail2ban itself doesn’t natively evaluate GeoIP rules, but you can enrich logs post-ban.
Example action script (
/etc/fail2ban/action.d/geoip-notify.conf
):
[Definition]
actionban = echo "Bannedfrom $(geoiplookup | cut -d: -f2)" >> /var/log/fail2ban-geoip.log
Enable it in a jail:
[sshd]
enabled = true
action = iptables[name=SSH] geoip-notify
Enable it in a jail:
[sshd]
enabled = true action = iptables[name=SSH] geoip-notify
Resulting log entry:
Banned 185.220.101.1 from Germany
This provides visibility without changing ban logic — a safe first step.
b. Use GeoIP-Aware Ban Policies
You can also adjust ban times based on country.
Example strategy:
- Short ban for local country
- Longer ban for known high-noise regions
This is usually implemented via multiple jails and post-processing scripts rather than direct GeoIP matching inside Fail2ban.
Best practice:
Let Fail2ban do behavior detection — let GeoIP provide context, not decisions.
9. GeoIP with nftables (Linux Modern Firewall Layer)
iptables +
xt_geoip
is considered legacy. On modern systems, nftables is the preferred approach.
a. Using GeoIP Sets in nftables
nftables does not natively include GeoIP, but you can integrate GeoIP via generated IP sets.
Workflow:
-
Convert GeoIP country IP ranges into nftables sets
-
Load them dynamically
Example set definition:
table inet filter {
set geo_block {
type ipv4_addr
flags interval
}
}
Populate the set using a script:
nft add element inet filter geo_block { 1.2.3.0/24, 5.6.0.0/16 }
Then apply it:
chain input {
type filter hook input priority 0;
ip saddr @geo_block drop
}
b. Automating GeoIP -> nftables
Typical automation pipeline:
GeoLite2 → country CSV → IP ranges → nftables set
Run this daily via cron.
Warning:
- Large country sets = memory usage
- Firewall reloads must be atomic
- Test on non-production systems first
10. GeoIP Dashboard: Turning Logs into Insight
Blocking is optional — insight is mandatory.
a. Simple GeoIP Log Dashboard (CLI-Based)
Apache example:
# awk '{print $NF}' /var/log/apache2/access.log | \
sort | uniq -c | sort -nr
Where $NF contains country code.
Sample Result:
1243 US
987 DE
422 FR
310 CN
This already tells a story.
b. Visual Dashboard with ELK / Grafana
For larger environments:
HAProxy / Apache -> JSON logs Enrich logs with GeoIP
Send to:
- ELK Stack
- Loki + Grafana
- Graylog
Metrics you want:
- Requests per country
- Errors per country
- Bans per country
- Login failures per country
This helps distinguish:
- Marketing traffic
- Legit users
- Background Internet noise
11. Create a Layered GeoIP Strategy
A sane, production-ready model using GeoIP would include something like:
-
Logging first
Apache / HAProxy logs with country codes -
Behavior detection
Fail2ban reacts to abuse -
Traffic shaping
HAProxy routes or rate-limits -
Firewall last
nftables drops only obvious garbage
GeoIP is strongest when it supports decisions, not when it makes them alone.
12. Best Practices to consider
- Prefer visibility over blocking
- Avoid blanket country bans
- Always log before denying
Combine GeoIP with:
- Fail2ban
- Rate limits
- CAPTCHA or MFA
- Keep GeoIP databases (regularly) updated
- Test rules with real IPs before deploying
13. Common Mistakes to Avoid
Blocking entire continents Using GeoIP as authentication Applying firewall GeoIP without logs Forgetting database updates Assuming GeoIP accuracy
Close up
GeoIP is not a silver bullet against vampire attacks – but when used thoughtfully, it becomes a powerful signal enhancer and can give you a much broader understanding on what is going on inside your network traffic.
Whether you’re using it to filter out segment of evil intruders based on logs, routing traffic intelligently, or filtering obvious abusea, GeoIP fits naturally into a layered security model and is used across corporations and middle and even small sized businesses nowadays.
Used conservatively, GeoIP follows the classic Unix philosophy:
Small datasets, Simple rules, Real-world effectiveness, combined with rest of tools it gives info and ways to protect better your networks and server infra.










No Comments »