如何在http请求中处理传入的自定义标头,然后根据结果反向代理请求

时间:2013-03-10 07:15:07

标签: nginx

我是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“with”my-header“,authserver将授权”my-header“并回复基于JSON的响应,如:

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

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

1 个答案:

答案 0 :(得分:0)

您需要根据nginx发出子请求。

您可以使用其中一个Eval模块,然后通过regexp解析响应,但不建议这样做。

推荐的方法是使用http://wiki.nginx.org/HttpLuaModule。 看一下http://openresty.org nginx bundle。

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发出的子请求默认会继承当前请求的所有请求标头。

相关问题