Sunday, 15 January 2012

lua - NGINX proxy_pass based on if-else conditions -



lua - NGINX proxy_pass based on if-else conditions -

problem statement

i proxy_pass url based on value nowadays in request header. request details including query parameter(if any), header , should passed proxy address.

what have tried

i have followed so post , based on requirement mentioned have tried following.

test.lua file

local token = ngx.var.http_authorization if token == "hello" -- ngx.print ("hello") local res = ngx.location.capture("/someurl") if res.status == 200 ngx.print(res.body) end end

nginx.conf

location /api/employees { content_by_lua_file test.lua; } location /someurl { internal; proxy_pass http://productionurl?q1=123&name=xyz; #proxy_redirect default; }

as can see passing query parameter manually in proxy_pass statement.

how resolve not passing actual request during proxy_pass ?

your problem resolved rewriting original request depending of header. here's example:

#sample backend set $backend_host "http://httpbin.org"; location ~*/api/employees { rewrite_by_lua ' --reading request headers local req_headers = ngx.req.get_headers() local target_uri = "" -- checking header value determine target uri if req_headers["x-special-header"] target_uri = req_headers["x-special-header"] else -- default path if not header found target_uri = "/get" end ngx.log(ngx.notice, string.format("resolved target_uri: %s", target_uri)) --rewriting uri according header (all original req args , headers preserved) ngx.req.set_uri(target_uri) '; proxy_pass $backend_host; }

sample request sending 'special' header path target backend:

curl 'http://localhost/api/employees?arg1=val1&arg2=val2' -h 'x-special-header: /headers'

response:

{ "headers": { "accept": "*/*", "connect-time": "0", "connection": "close", "host": "httpbin.org", "total-route-time": "0", "user-agent": "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 nss/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2", "via": "1.1 vegur", "x-request-id": "6e515e0a-0061-4576-b1aa-5da3e3308c81", "x-special-header": "/headers" }

sample request without 'special' header:

curl 'http://localhost/api/employees?arg1=val1&arg2=val2'

response:

{ "args": { "arg1": "val1", "arg2": "val2" }, "headers": { "accept": "*/*", "connect-time": "4", "connection": "close", "host": "httpbin.org", "total-route-time": "0", "user-agent": "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 nss/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2", "via": "1.1 vegur", "x-request-id": "520c0e12-1361-4c78-8bdf-1bff3f9d924c" }, "url": "http://httpbin.org/get?arg1=val1&arg2=val2" }

nginx lua

No comments:

Post a Comment