首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >openresty在post请求体数据中搜索关键字

openresty在post请求体数据中搜索关键字
EN

Stack Overflow用户
提问于 2022-11-08 06:49:03
回答 2查看 54关注 0票数 0

我一直在使用openresty进行简单的请求转发,它正在按预期工作,我使用以下代码将每个传入请求转发到另一个URL:

代码语言:javascript
复制
        location /app/ {
        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;

我用下面的代码记录每个帖子请求:

代码语言:javascript
复制
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;
               }

现在,我的要求是,在转发每个请求之前,我希望筛选针对特定字符串/关键字的post请求正文数据,如果在post数据中找到特定的字符串/关键字,则只应该将其转发到代理URL https://example.com/abc/

我做了一些研究,但没有找到任何帮助我做到这一点,谁能帮忙吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-11-25 13:18:53

最后我在lua的帮助下完成了这件事:

代码语言:javascript
复制
location /app/ {
.
.
.
    
access_by_lua '
            ngx.req.read_body()
            local data = ngx.req.get_body_data()
            local  match = ngx.re.match(ngx.var.request_body, "<reqid>search</reqid>")                      

#local  match = ngx.re.match(ngx.var.request_body, "<reqid>search</reqid>","i") for case insensitive match          
            
            if match then
                #nothing to do
            else
                return ngx.exit(ngx.HTTP_FORBIDDEN)
            end';
            proxy_pass      https://example.com/abc/;
            
}   

在这里,请求体数据将被赋值给变量' data‘,使用ngx.re.match,我们可以将字符串/关键字与请求体数据匹配,在上面的示例中,如果在请求正文中找不到<reqid>search</reqid>,那么它将返回403禁止的,如果找到,它将被传递给proxy_pass。

在处理之前,它对于过滤传入的请求非常有用。

票数 0
EN

Stack Overflow用户

发布于 2022-11-08 07:27:40

对Lua不太了解,但希望这能帮上忙:

代码语言:javascript
复制
location /app {
        set $flag_true 1;
        set_by_lua $flag '
            local token = ngx.var.arg_token
            local request_body = ngx.req.get_body_data()
            ngx.req.read_body()

            # do your filtering here 
            if string.find(request_body, "tiger") then
                return ngx.var.flag_true
            end
            return "false"
        ';
        if ($flag = 1) {
            proxy_pass http://x.x.x.x:8092;
            break;
        }
        echo "You do not have permission: $flag";
    }

灵感来源于:

Filter request on proxy_pass using lua on nginx

How to check if matching text is found in a string in Lua?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74356646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档