首页 > 解决方案 > nginx匹配请求体而不使用lua模块

问题描述

nginx 有没有办法根据请求正文是否有字符串来做某事?我确信我可以使用 Lua 模块来做到这一点。我试图找出是否有单独使用 nginx 的方法。

我希望像下面这样的东西会起作用。

 location /students-api {
    if ($request_body ~* "(.*)specialstudent(.*)" ) {
      set  $student_status  'special';
    }
  // and use student_status for some logic
 } 

标签: nginxnginx-reverse-proxynginx-config

解决方案


我认为它应该可以工作,但是需要对其进行测试。实际上我$request_body只用于日志记录,不确定它是否在请求处理的重写阶段可用。这是官方的描述,上面写着:

当请求正文被读取到内存缓冲区时,该变量的值在由 、 、 和 指令处理的proxy_pass位置fastcgi_passuwsgi_pass可用。scgi_pass

此外,如果您以后不使用它们(实际上您只是浪费资源将它们保存在内存中),则不需要这些捕获组来检查变量是否存在子字符串,就if ($request_body ~* "specialstudent") { ... }足够了。

更新

这是另一种有更多工作机会的方法,因为proxy_add_header指令肯定在请求处理的重写阶段之后执行:

map $request_body $special {
    ~*"specialstudent"    "special";
    # otherwise '$special' variable value will be empty
}
server {
    ...
    location /students-api {
        ...
        proxy_set_header X-Student-Status $special;
        ...
    }
}

更新 2

在测试了所有这些之后,我可以确认该if方法不起作用:

server {
    ...
    location /students-api {
        if ($request_body ~* "specialstudent") {
            set $student_status "special";
        }
        proxy_set_header X-Student-Status $student_status;
        ...
    }
}

正如预期的那样,$request_body变量在请求处理的重写阶段没有被初始化。但是,该map方法按预期工作:

map $request_body $student_status {
    ~*"specialstudent"    "special";
    # otherwise '$special' variable value will be empty
}
server {
    ...
    location /students-api {
        proxy_set_header X-Student-Status $student_status;
        ...
    }
}

真正让我吃惊的是,下面的例子没有设置两个标题中的任何一个:

map $request_body $student_status {
    ~*"specialstudent"    "special";
    # otherwise '$special' variable value will be empty
}
server {
    ...
    location /students-api {
        if ($request_body ~* "specialstudent") {
            set $student_special "special";
        }
        proxy_set_header X-Student-Status $student_status;
        proxy_set_header X-Student-Special $student_special;
        ...
    }
}

$request_body在请求处理的早期重写阶段以某种方式访问​​变量也会导致map翻译停止工作。我现在没有对这种行为的解释,如果有人能解释这里发生的事情,我将不胜感激。


推荐阅读