nginx - nginx匹配请求体而不使用lua模块
问题描述
nginx 有没有办法根据请求正文是否有字符串来做某事?我确信我可以使用 Lua 模块来做到这一点。我试图找出是否有单独使用 nginx 的方法。
我希望像下面这样的东西会起作用。
location /students-api {
if ($request_body ~* "(.*)specialstudent(.*)" ) {
set $student_status 'special';
}
// and use student_status for some logic
}
解决方案
我认为它应该可以工作,但是需要对其进行测试。实际上我$request_body
只用于日志记录,不确定它是否在请求处理的重写阶段可用。这是官方的描述,上面写着:
当请求正文被读取到内存缓冲区时,该变量的值在由 、 、 和 指令处理的
proxy_pass
位置fastcgi_pass
中uwsgi_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
翻译停止工作。我现在没有对这种行为的解释,如果有人能解释这里发生的事情,我将不胜感激。
推荐阅读
- sql - 使用 ROW_NUMBER () OVER(PARTITION BY... ORDER BY) 更新语句
- amazon-web-services - Redshift 或平面设计中的维度建模 - 成本与时间
- java - Kotlin 如何使用 JDK 1.8 调用 Java 11 代码?
- python - 如何加载和解析 JSON 文件
- scala - Spark从每个镶木地板文件中获取一行
- reporting-services - 报表生成器 - 连接字符串 - 在 1 个地方工作,但在另一个地方不工作
- java - 如何将 Java CRC32 校验和计算转换为 PHP 代码
- java - 使用 Retrofit 2 发布原始 JSON
- javascript - 如何在discord js中检测嵌入消息的特定单词
- javascript - 如何使用节点js将对象数组插入表