Calling external api in Nginx location section

雨燕双飞 提交于 2021-01-24 13:51:41

问题


I am trying to resolve proxy_pass value dynamically (through web api) in nginx.

I need something like below;
Example taken from: https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

location /proxy-pass-uri {
    set $urlToProxy = CallWebAPI("http://localhost:8081/resolver?url=" + $url);
    proxy_pass $urlToProxy;         
}

So, my question is that, is it possible to make HTTP request or to write method such as CallWebAPI?

I know it might be a bad practice, but the website I am dealing with has thousands of web urls, which are mapped as key-value pairs, and 90% of them does not obey any specific regex rules. So I have content mapped database, and I need to fetch incoming url with content dynamically.

I am trying to use a very light web service to look up URLs from redis, and return proxy url.

Would this be a valid scenario, or is there any other built in solution in nginx like this?


回答1:


I doubt this can be done with "pure" nginx, but this definitely can be done with openresty or ngx_http_lua_module with the help of ngx.location.capture method. For example:

resolver 8.8.8.8;
location ~/proxy-pass-uri(/.*)$ {
    set $url $1;
    set $proxy "";
    access_by_lua_block {
       res = ngx.location.capture("http://localhost:8081/resolver?url=" .. ngx.var.url)
       ngx.var.proxy = res.body
    }
    proxy_pass $proxy$url;
}

There is also an ngx_http_js_module (documentation, GitHub) which have an ability to do subrequests (example), but I never used it and cannot tell if it can be used this way.



来源:https://stackoverflow.com/questions/53799389/calling-external-api-in-nginx-location-section

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!