You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenResty Nginx中过滤POST请求体关键词后再转发请求?

基于OpenResty实现POST请求体关键词过滤转发

核心思路

借助OpenResty的Lua扩展能力,先读取POST请求体内容,检查是否包含目标关键词,仅在满足条件时才执行后续的代理转发逻辑。

完整配置示例

server {
    # 保留原有日志格式配置
    log_format post_logs '[$time_local] "$request" $status '  
        '$body_bytes_sent "$http_referer" '        
        '"$http_user_agent" [$request_body]';

    location /app/ {
        access_log  logs/post.log post_logs;

        # 强制读取请求体到内存,让Lua能获取请求体内容
        lua_need_request_body on;

        # 前置执行Lua检查逻辑
        access_by_lua_block {
            -- 替换为你需要匹配的目标关键词
            local target_keyword = "your_target_keyword"
            local request_body = ngx.var.request_body or ""

            -- 仅对POST请求做关键词检查
            if ngx.req.get_method() == "POST" then
                -- 检查请求体是否包含关键词,不包含则直接拒绝请求
                if not string.find(request_body, target_keyword) then
                    ngx.exit(ngx.HTTP_FORBIDDEN)
                end
            end
        }

        # 保留原有代理转发配置
        proxy_pass      https://example.com/abc/;
        proxy_read_timeout 60s;         
        proxy_pass_header Server;
        proxy_set_header          Host            $host;
        proxy_set_header          X-Real-IP       $remote_addr;
        proxy_set_header          X-Forwarded-For $proxy_add_x_forwarded_for;
        add_header  X-Frame-Options "SAMEORIGIN" always;
    }
}

关键配置说明

  • lua_need_request_body on;:必须开启该指令,否则ngx.var.request_body无法获取到POST请求体内容。如果业务中有大请求体场景,需配合调整client_max_body_size参数,避免内存占用过高。
  • access_by_lua_block:在请求进入代理转发流程前执行Lua代码,先判断请求方法是否为POST,再检查请求体关键词。不满足条件时直接返回403状态码,终止请求;满足条件则继续执行代理转发。
  • 若需要复杂匹配规则,可将string.find替换为ngx.re.match使用正则表达式,示例:if not ngx.re.match(request_body, "your_regular_expression", "io") then。

扩展场景处理

如果请求体是JSON格式,可通过cjson库解析后精准检查字段值:

local cjson = require "cjson"
local ok, body_table = pcall(cjson.decode, request_body)
-- 假设要检查JSON中的"target_field"字段是否等于指定值
if ok and body_table and body_table.target_field == "expected_value" then
    -- 符合条件,继续转发
else
    ngx.exit(ngx.HTTP_FORBIDDEN)
end

内容的提问来源于stack exchange,提问作者user2338456

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:35:26