如何处理http请求中的传入custorm标头

如何处理http请求中的传入custorm标头

本文介绍了如何处理http请求中的传入custorm标头,然后反向代理请求取决于结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Nginx的新手,我的要求非常像这样:

I am newbie for Nginx, my requirement is pretty much like this:

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

I set up Nginx as an front end service before my service, that's like an reverse proxy server, while I need any incoming http request be handled based on incoming customer headers. I know I can set reverse proxy like following:

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的响应,例如:

I also know getting incoming "my-header" from incoming request by using $http_my_header, what i need is, retrieve the "my-header" from request, and call another remote web service like "http: //authserver:authport/authorize" with "my-header" in request header, and authserver will authorize the "my-header" and reply a JSON based response like:

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

然后,我需要基于响应有效"值来决定将proxy_pass的请求传递给位于nginx后面的myservice,或使用403 http响应直接拒绝.

then I need to based on the response "valid" value to decide proxy_pass the request to myservice behind nginx or direct deny with 403 http response.

推荐答案

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

You need to issue a subrequest in terms of nginx.

您可以使用Eval模块之一执行此操作,然后通过regexp解析响应,但是不建议这样做.

You may do it using one of Eval modules and then parse response by regexp, but it is not recommended.

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

The recommended way is to use http://wiki.nginx.org/HttpLuaModule.Take a look at 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发出的子请求继承了当前请求的所有请求标头.

Note that subrequests issued by ngx.location.capture inherit all the request headers of the current request by default.

这篇关于如何处理http请求中的传入custorm标头,然后反向代理请求取决于结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:50