.htaccess: A Helper Script to Easily Block Website Traffic by Country
Published on Sep 3, 2025, filed under tools, development, politics. (Share this post, e.g., on Mastodon.)
This is one of 180 articles that you can also read in an ebook: On Web Development II.
If you run your own website (which, if a web developer peer, you benefit from), there’s a good chance you run it on Apache.
Whatever the motivation for you to consider this—though after all, there are countries attacking, invading, and occupying other countries (e.g., Russia, Israel) and countries committing genocides (e.g., Israel)—, here’s one simple approach to geographic IP blocking via .htaccess:
- Use a bash helper script to pull country IP ranges via IPdeny and generate the respective block list
- Add the script output to your .htaccess and upload the updated file
- That’s it
Is that really it? Well, you’d want to keep those lists up-to-date, so you could set up a cron job and/or a reminder to update the lists periodically.
What does that helper script do? It’s straightforward: Pull data from IPdeny for whatever countries you specify, and wrap the data in an .htaccess-ready RequireAll block.
What’s not so straightforward are the performance-related options (the code for these, that is): You can, for example, use --min-prefix 16 only to include large network blocks (like /13, /14, /15, /16), while excluding smaller subnets (like /24, /30, /32). This can reduce thousands of IP ranges down to a couple of hundred, for much better Apache performance.
IPdeny appears to be relatively conservative, so even the default approach shouldn’t over-block. And while it won’t deny all traffic from specified regions, it could serve whatever your motivation—whether that’s compliance, testing, or making a statement.
As one action to take as part of a personal policy, please keep donating to people and nations currently under attack, like Ukraine and Palestine. Thank you.
About Me
I’m Jens (long: Jens Oliver Meiert), and I’m an engineering lead, guerrilla philosopher, and indie publisher. I’ve worked as a technical lead and engineering manager at various companies (e.g., Google); I’m an active web and tool developer (code optimization, digital defense), a contributor to web standards (like HTML, CSS, WCAG), and a book author (O’Reilly, Frontend Dogma).
I love trying things—in web development and engineering management, but also in politics and philosophy, where I hold to one idea in particular: that we can only be well if we take good care of everyone. Here on meiert.com I talk about some of my perspectives and experiences. (Please share feedback: Interpret charitably, keep it friendly, but do be critical.)
