Creating a simple IP blacklist with mod_rewrite and RewriteMap

September 6, 2013 by Michael

I’ve had a lot of URL spam (bots testing URLs for weaknesses and exploits). They haven’t been successful but i have configured my system to send me an e-mail when exceptions occurs and there have a been a lot of e-mails.

I wanted a simple solution with the following features:

  • No additional packages to install
  • No server restarts when the blacklist changes

In the given setup Apache is merely a proxy to my backend and a simple .htaccess inside the root directory with a lot of ip entries wouldn’t work. Instead this would have gone into the vhost definition which means server restarts / reloads.

I came up with the idea using the RewriteMap directive of mod_rewrite.

You can ask a RewriteMap for a value with anything ModRewrite and apache variables give you.

This is what my map (blacklist.txt) looks like:

111.73.45.82    b
111.73.45.151   b
111.73.45.164   b

I use httxt2dbm to create DBM Hash File

httxt2dbm -i blacklist.txt -o blacklist.dbm

and then in my vhost definition:

RewriteMap ipmap dbm:/etc/apache2/sites-available/blacklist.dbm 
RewriteCond ${ipmap:%{REMOTE_ADDR}} ^b$            [NC]
RewriteRule .* - [F,L]

That means:

Use the given blacklist.dbm as map named ipmap. Than ask for the value for the given remote address. If the value is “b” than deny access to all pages.

Simple, but effective.

One comment

  1. Weil Jimmer wrote:

    Good tutorial.

    Posted on February 27, 2017 at 10:21 AM | Permalink
Post a Comment

Your email is never published nor shared. Required fields are marked *