在 Nginx 位置部分调用外部 api [英] Calling external api in Nginx location section

查看:101
本文介绍了在 Nginx 位置部分调用外部 api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 nginx 中动态解析 proxy_pass 值(通过 web api).

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

我需要像下面这样的东西;
示例取自:https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

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;         
}

那么,我的问题是,是否可以发出 HTTP 请求或编写 CallWebAPI 之类的方法?

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

我知道这可能是一个不好的做法,但我正在处理的网站有数千个网址,它们被映射为键值对,其中 90% 不遵守任何特定的正则表达式规则.所以我有内容映射数据库,我需要动态获取带有内容的传入 url.

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.

我正在尝试使用一个非常轻量级的 Web 服务从 redis 中查找 URL,并返回代理 URL.

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

这是否是一个有效的场景,或者在 nginx 中是否有其他类似的内置解决方案?

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

推荐答案

我怀疑这可以用纯" nginx 来完成,但这绝对可以用 openrestyngx_http_lua_modulengx.location.capture 方法的帮助.例如:

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;
}

还有一个 ngx_http_js_module (文档, GitHub) 有能力做子请求 (example),但我从未使用过它,也不知道是否可以这样使用.

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.

这篇关于在 Nginx 位置部分调用外部 api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆