NGINX - OpenResty - How to reverse proxy a call to 2 different servers based based on a string?
You almost did it youself, the only thing I would do differently is to use rewrite_by_lua
instead of content_by_lua
:
location / {
set $proxy "";
rewrite_by_lua '
ngx.req.read_body()
local match = ngx.re.match(ngx.var.request_body, "STRING TO FIND")
if match then
ngx.var.proxy = "www.ServerA.com"
else
ngx.var.proxy = "www.ServerB.com"
end
';
proxy_pass http://$proxy$uri;
}
If request is not an HTTP POST or has an empty body, ngx.req.read_body()
will return nil
, so it is better to add an additional check:
location / {
set $proxy "";
rewrite_by_lua '
ngx.req.read_body()
local body = ngx.var.request_body
if (body) then
local match = ngx.re.match(body, "STRING TO FIND")
if match then
ngx.var.proxy = "www.ServerA.com"
else
ngx.var.proxy = "www.ServerB.com"
end
else
ngx.status = ngx.HTTP_NOT_FOUND
ngx.exit(ngx.status)
end
';
proxy_pass http://$proxy$uri;
}
You also can limit allowed methods:
location / {
limit_except POST { deny all; }
...
}
One more thing. With this configuration, if you specify your backends with domain names instead of IP addresses, you'll need a resolver
directive in your config. You can use your local name server if you have one, or use something external like Google public DNS (8.8.8.8) or DNS provided for you by your ISP.