2014-10-16 2 views
1

문제 설명의 nginx의 proxy_pass에 기반하는 경우 - 다른 조건

는 요청 헤더의 일부 값 존재에 따라 다른 URL로 proxy_pass합니다. 쿼리 매개 변수 (있는 경우), 헤더 및 모든 것을 포함하여 모든 요청 세부 정보는 프록시 주소로 전달되어야합니다. 내가 SO post을 따라 요구 사항을 기반으로 한

을 시도 무엇

나는 다음을 시도 언급했다.

Test.lua의

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

nginx.conf 파일

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

당신은 내가 proxy_pass 성명에서 수동으로 쿼리 매개 변수를 전달하고 볼 수 있듯이.

proxy_pass 동안 실제 request을 전달하지 않음으로써 어떻게 해결할 수 있습니까?

답변

2

헤더에 따라 원래 요청을 다시 작성하면 쉽게 문제를 해결할 수 있습니다.

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

응답 :

{ 
    "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 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 an a header value to determine target uri 
      if req_headers["x-special-header"] then 
       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 to header (all original req args and headers are preserved) 
      ngx.req.set_uri(target_uri) 
     '; 
     proxy_pass $backend_host; 
} 

샘플 요청 전송'특별한 '헤더 : 다음은 예입니다 '헤더 :

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

응답 :

{ 
    "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" 
}