Nginx:将请求分派到多个端点

Nginx : dispatch request to multi endpoints

我的目标是从其他服务器删除文件,因此我需要同时将请求分派到这些端点。

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

执行时出现错误:

"proxy_pass" directive is duplicate

任何建议都会有所帮助

这是我建议的一个例子:

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

请参阅 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 文档章节。