Home > OS >  Nginx : dispatch request to multi endpoints
Nginx : dispatch request to multi endpoints

Time:04-17

My goal is to delete a file from another servers for that reason i need to dispatch the request into these endpoints at the same time.

location / {
   
   set_by_lua_block $url_format {
   .. block lua for string manipulation and constructing which return as example '/images/test.png'
   }
   
  set $cdn1 "http://server1.com";
  set $cdn2 "http://server2.com";
   
  proxy_set_header Host main-server.com;
  proxy_pass $cdn1$url_format;
  proxy_pass $cdn2$url_format;
}

When executing, I get the error :

"proxy_pass" directive is duplicate

Any suggestion will be helpful

CodePudding user response:

Here is an example of what I was suggesting:

location / {
    set_by_lua_block $url_format {
        -- block lua for string manipulation and constructing which return as example '/images/test.png'
    }
    # variables should be pre-initialized
    set $cdn '';
    set $url '';
    content_by_lua_block {
        local cdns = { "http://server1.com", "http://server2.com" }
        local reqs = {}
        for _, cdn_name in ipairs(cdns) do
            table.insert(reqs, { "/dispatcher", { vars = { cdn = cdn_name, url = ngx.var.url_format } } })
        end
        local resps = { ngx.location.capture_multi(reqs) }
        -- analyze 'resps' table here, generate response (see ngx.say, ngx.exit functions)
    }
}

location /dispatcher {
    internal;
    resolver 8.8.8.8; # use any resolver that is able to resolve server1.com, server2.com etc.
    proxy_pass $cdn$url;
}

See this article for the decription why do you need a resolver directive here. Most likely you can move your code from the set_by_lua_block to the content_by_lua_block to slightly simplify the config. If you need some specific HTTP request method (e.g. DELETE) to be used, see HTTP method constants documentation chapter.

  • Related