gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:57:49 27 4
gpt4 key购买 nike

我正在创建一个简单的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com