我有一个nginx设置,用于反向代理到我的后端服务器。我有一个要求,我需要发送流量到一个IP,如果它是从另一个HTTP请求成功检索,否则发送到另一个IP。比如我有一个带有request_param=abcd的传入请求(它可以是任何值)。如果我能够从http://service/abcd中检索到,则将其路由到IP1,否则将其路由到IP2。
如下所示:
server {
location /${abcd} {
if(http://service/$abcd returns HTTP 200)
then proxy_pass http://$http_host_1$request_uri;
else
proxy_pass http://$http_host_2$request_uri;
...
}
}
发布于 2019-11-30 00:48:43
Openresty就是这个问题的解决方案-它构建在nginx之上,让我们配置lua代码来拦截nginx请求处理,并放入我们的自定义代码。https://openresty-reference.readthedocs.io/en/latest/Directives/
我在访问阶段使用rewrite_by_lua根据条件重定向请求。
还需要使用库lua-resty-http来发出外部请求。
cd /usr/local/openresty/lualib/resty curl -O https://raw.githubusercontent.com/ledgetech/lua-resty-http/v0.15/lib/resty/http.lua curl -O https://raw.githubusercontent.com/ledgetech/lua-resty-http/v0.15/lib/resty/http_headers.lua
server {
listen 443;
location /location {
lua_need_request_body on;
set $backendurl 'http_host_1/request_uri';
rewrite_by_lua_block {
local body = ngx.req.get_body_data()
local abcd = ""
if (body) then
abcd = string.match(body, "my_pattern")
if (abcd ~= nil and abcd ~= '') then
local http = require "resty.http"
local httpc = http.new()
local external_url = "http://service/" .. abcd
local res, err = httpc:request_uri(external_url, {
method = "GET",
headers = {
["Content-Type"] = "application/json"
}
})
local response_status = res.status
if response_status == 404 then
ngx.var.backendurl = "http_host_2"
end
end
end
}
proxy_pass http://$backendurl/$uri;
}
}
https://stackoverflow.com/questions/57751444
复制