python - mod_rewrite RewriteMap prg 仅适用于第一个请求

标签 python apache mod-rewrite

我正在创建一个简单的 IP 黑名单。每个请求都根据 IP 列表进行评估,并在必要时抛出 403。我决定在 Apache 端使用 mod_rewrite、它的 RewriteMap 和简单的 python 脚本来处理它。

虚拟主机中:

<VirtualHost *:80>
    ...

    RewriteEngine On

    RewriteMap banip prg:/path/to/script.py
    RewriteCond ${banip:%{REMOTE_ADDR}} !=OK
    RewriteRule ^/.* - [F]
</VirtualHost>

脚本.py:

#!/usr/bin/python
import sys

sys.stdout.write('OK\n')
sys.stdout.flush()

现在是奇怪的部分。重启 Apache 后,只有第一个请求返回 200,随后的每个请求都返回 403。我希望它们都返回 200。当我重新启动 Apache 时,同样的事情再次发生。

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

在第二次刷新时,它不会写入任何来重写日志,只是直接抛出 403

当我尝试 RewriteCond OK !=OKRewriteCond NOTOK !=OK 时,它运行完美。知道为什么会这样吗?

我在 Xubuntu 11.10 上使用 Apache 2.2.20 和 Python 2.7.2。

最佳答案

我想你可能想仔细看看 RewriteMap documentation .特别是:

This program is started once, when the Apache server is started, and then communicates with the rewriting engine via its stdin and stdout file-handles. For each map-function lookup it will receive the key to lookup as a newline-terminated string on stdin. It then has to give back the looked-up value as a newline-terminated string on stdout or the four-character string ``NULL'' if it fails (i.e., there is no corresponding value for the given key).

因此,您的程序启动一次,从 Apache 接收 key ,生成响应,然后退出。正如您从文档中看到的那样,它不会重新启动

您的程序应该循环,读取一行输入,生成输出,然后等待更多输入。链接文档包含一个非常简短的示例。

关于python - mod_rewrite RewriteMap prg 仅适用于第一个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8392159/

相关文章:

php - Apache 优雅重启 - 是否影响当前 PHP 脚本执行

php - .htaccess 前 3 个字符作为文件夹

regex - 通过 htaccess 将部分添加到 URL

apache - mod_rewrite 在 apache24 中强制使用 ssl

python - 将不同行的 csv 写入保持相同标题的列中? - Python

python - 无法在 python 中加载 json 文件

php - UTF-8贯穿始终

.htaccess - 使用 Htaccess 和 Mod_Rewrite 重写 SEO 友好 URL

python - 在 PyYAML 中使用自定义类键反序列化字典失败

python - Lambda 表达式及其等效代码