Search code examples
nginxreverse-proxynginx-upstreams

Redirect all the headers from upstream to another location in nginx


Could you please tell me if it's possible to redirect all the headers in nginx from upstream /auth_gateway to /connection. My request and nginx configuration

curl -silent -include -X 'GET' -H 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJZa0hadkt5YUJuNU9oaVF6d3kxWXduNFBHYm5RSDV0aDh1ZkhOWHZiTVdrIn0' -H 'x-realy-company: google' -H 'x-realy-request-id: 12545787' https://mycooldomain.org/connection/

New headers will be to add on the authorization service /auth_gateway, such as x-realy-privileges, x-realy-user and others.

location ~* ^/connection/ {
            if ($http_authorization !~ "^Bearer .{20,}"){
                return 403 "Not authorized";
            }
            auth_request /auth_gateway;
            auth_request_set $auth_status $upstream_status;
            proxy_pass http://10.xx.xx.xx:8080;
        }
        
location = /auth_gateway {
            proxy_pass http://10.xx.xx.xx:8081/authorize;
            proxy_set_header X-Original-URI $request_uri;
        }

x-realy-user: da82fe4b-d0ef-477e-a3d1-facc78b605c7

x-realy-privileges: 1,2,3,4,5,6,7,8,9,10

x-realy-global-roles: ROLE_OPERATOR

x-realy-okt-id: da82fe4b-d0ef-477e-a3d1

These headers are extracted from the Bearer authorization token and I would like to redirect them to the /connection

Thanks and advance!


Solution

  • Well, I did it via lua module. I hope this helps someone in the future.

    full code here

    location ~* ^/connection/ {
                if ($http_authorization !~ "^Bearer .{20,}"){
                    return 403 "Not authorized";
                }
                auth_request /auth_gateway;
                auth_request_set $auth_status $upstream_status;
                
                rewrite_by_lua_block {
                    local res1 = ngx.location.capture("/auth_gateway", {method=ngx.HTTP_GET, args=args})
                    local concat = table.concat
                    for name, value in pairs(res1.header) do
                        if type(value) == "table" then
                            ngx.req.set_header(name, concat(value, ", "))
                        else
                            ngx.req.set_header(name, value)
                        end
                    end
                }
                
                proxy_pass http://10.xx.xx.xx:8080;
            }
            
    location = /auth_gateway {
                proxy_pass http://10.xx.xx.xx:8081/authorize;
                proxy_set_header X-Original-URI $request_uri;
            }