【问题标题】:How to process incoming custorm headers in http request and then reverse proxy the request depend on the result如何处理 http 请求中传入的 custorm 标头然后反向代理请求取决于结果
【发布时间】:2013-03-10 07:15:07
【问题描述】:

我是Nginx的新手,我的需求差不多是这样的:

我在我的服务之前将 Nginx 设置为前端服务,这就像一个反向代理服务器,而我需要根据传入的客户标头处理任何传入的 http 请求。我知道我可以设置如下反向代理:

server {
    listen      18080;
    server_name localhost;

    location /myService {
            proxy_pass http://host:port/myservice/;
    }

}

我还知道使用 $http_my_header 从传入请求中获取传入的“my-header”,我需要的是从请求中检索“my-header”,然后调用另一个远程 Web 服务,例如“http://authserver: authport/authorize”在请求标头中带有“my-header”,authserver 将授权“my-header”并回复基于 JSON 的响应,例如:

{
   valid: "true"/"false";
}

然后我需要根据响应“有效”值来决定 proxy_pass 请求到 nginx 后面的 myservice 或直接拒绝 403 http 响应。

【问题讨论】:

    标签: nginx


    【解决方案1】:

    您需要在 nginx 方面发出子请求。

    您可以使用 Eval 模块之一,然后通过正则表达式解析响应,但不建议这样做。

    推荐的方式是使用http://wiki.nginx.org/HttpLuaModule。 看看http://openresty.org nginx 捆绑包。

    init_by_lua 'require "cjson"';
    
    location /auth {
        proxy_pass http://authserver:12345/authorize;
    }
    location /myService {
        access_by_lua '
            res = ngx.location.capture("/auth")
            if res.status == ngx.HTTP_OK then
                local response = cjson.decode( res.body )
                if response.valid and response.valid == "true" then
                    return
                end
            end
            ngx.exit(ngx.HTTP_FORBIDDEN)
        ';
        proxy_pass http://host:port/myservice/;
    }
    

    注意,ngx.location.capture 发出的子请求默认继承当前请求的所有请求头。

    【讨论】:

    • 谢谢。您提供的示例就像请求发送到 authserver 并根据 auth 结果,nginx 决定 proxy_pass 是否发送给 myservice。如果请求直接发送到 myservice 并且我只想在它 proxy_pass 之前由 authserver 授权它?
    • @Jim Song 抱歉,没有看到您的评论。你错了,位置是 /myService 所以请求直接到 myService。我向 authserver 发出子请求
    猜你喜欢
    • 2010-09-24
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多