I’m creating a simple IP blacklist. Each request is evaluated against list of IPs and throws 403 if necessary. I decided to deal with it on Apache side with mod_rewrite, its RewriteMap and simple python script.
In VirtualHost:
<VirtualHost *:80>
...
RewriteEngine On
RewriteMap banip prg:/path/to/script.py
RewriteCond ${banip:%{REMOTE_ADDR}} !=OK
RewriteRule ^/.* - [F]
</VirtualHost>
script.py:
#!/usr/bin/python
import sys
sys.stdout.write('OK\n')
sys.stdout.flush()
Now the weird part. After restart of Apache, only first request returns 200 and every following request returns 403. I’d expect all of them to return 200. When I restart Apache, the same happens all over again.
Rewrite log after restart of Apache:
# Very first request
127.0.0.1 - (2) init rewrite engine with requested uri /app_dev.php/
127.0.0.1 - (3) applying pattern '^/.*' to uri '/app_dev.php/'
127.0.0.1 - (5) map lookup OK: map=banip key=127.0.0.1 -> val=OK
127.0.0.1 - (4) RewriteCond: input='OK' pattern='!=OK' => not-matched
127.0.0.1 - (1) pass through /app_dev.php/
...
# Request after that
127.0.0.1 - (2) init rewrite engine with requested uri /static/css/grid.css
127.0.0.1 - (3) applying pattern '^/.*' to uri '/static/css/grid.css'
127.0.0.1 - (5) map lookup OK: map=banip key=127.0.0.1 -> val=
127.0.0.1 - (4) RewriteCond: input='' pattern='!=OK' => matched
127.0.0.1 - (2) forcing responsecode 403 for /static/css/grid.css
On second refresh, it doesn’t write anything to rewrite log, just throws 403 straight away.
When I try RewriteCond OK !=OK or RewriteCond NOTOK !=OK, it works perfect. Any idea why is this happening?
I’m on Xubuntu 11.10 with Apache 2.2.20 and Python 2.7.2.
I think you may want to take a close look at the RewriteMap documentation. In particular:
So, your program gets started once, receives a key from Apache, generates a response, and then exits. As you can see from the documentation, it will not get restarted.
Your program should loop, reading a line of input, generating output, and then waiting for more input. The linked documentation includes a very short example.