作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有一个在 nginx 后面运行的应用程序。为了允许客户在同一主机名下添加他们自己的工具,我们使用类似这样的 location
:
location /some-extension {
rewrite ^/(.*) /$1 break;
proxy_pass http://customers-app/$1/$args;
}
现在,我想让这个动态化,以便给定的客户可以创建零个或多个这样的位置。由于该应用程序是使用 Docker 部署的,因此我无法手动编辑 nginx 配置。
Nginx 是用 perl 和 lua 支持编译的,所以我在想这样的事情:
path1 url1 path-2 url2 ... pathn urln
形式的环境变量来配置外部工具。location
配置中,将请求URL的第一个路径段与环境变量和proxy_pass
匹配到相应的URL(如果找到)。到目前为止,这是我所拥有的:
location / {
content_by_lua '
local target_path = ngx.var.uri;
local name = nil
if target_path:len() > 0 then
startAt = target_path:find("/") + 1
endAt = target_path:find("/", startAt) - 1
name = target_path:sub(startAt,endAt)
ngx.say(name)
end
if name then
local custom_proxies = os.getenv("CUSTOM_PROXIES");
inString = custom_proxies:find("another ")
if not inString then
ngx.say("not in string")
else
startAt = custom_proxies:find(" ", inString + 1) + 1
endAt = custom_proxies:find(" ", startAt)
url = custom_proxies:sub(startAt,endAt)
ngx.say(url)
end
end
';
}
我知道我不应该使用 content_by_lua
但它似乎有点工作。问题是我怎样才能将它 proxy_pass
到指定的 URL?
最佳答案
我是这样解决的:
环境变量应该是以空格分隔的名称和 URL 列表; key http://example.com/app1 key2 http://acme.com
。
Lua 脚本将环境变量读入表
,其中以key
为键,以下 URL 为值。
nginx location
block 将处理请求并使用 Lua 脚本找到要代理的模块。
函数将接受请求路径并从中找到键,然后在表中查找 URL。
这是脚本:
local custom_proxies = os.getenv("CUSTOM_PROXIES")
local custom_modules = {}
local cutFrom = 0
local cutTo = 0
while cutTo < custom_proxies:len() do
cutFrom = cutTo
cutTo = custom_proxies:find(" ", cutFrom + 1)
local name = custom_proxies:sub(cutFrom, cutTo - 1)
cutFrom = cutTo + 1
cutTo = custom_proxies:find(" ", cutFrom)
if not cutTo then
cutTo = custom_proxies:len() + 1
end
local url = custom_proxies:sub(cutFrom, cutTo - 1)
custom_modules[name] = url
cutTo = cutTo + 1
end
function custom_modules.get_url(target_path)
local name = nil
local startAt = target_path:find("/", 6) + 1
local endAt = target_path:find("/", startAt)
if not endAt then
endAt = target_path:len()
else
endAt = endAt - 1
end
name = target_path:sub(startAt,endAt)
if name then
return custom_modules[name]
else
ngx.log(ngx.STDERR, "Not able to deduct module name from URI")
return ""
end
end
return custom_modules
这是 nginx 位置
:
location /custom/ {
set_by_lua $redirect_to '
local custom_modules = require "read_proxies"
local url = custom_modules.get_url(ngx.var.uri)
if not url then
ngx.log(ngx.STDERR, "Not a known custom module.")
end
return url
';
if ($redirect_to = '') {
return 404 'Unknown custom module.';
}
rewrite ^/custom/\w+/(.*) /$1 break;
proxy_pass $redirect_to$1?$args;
}
想法是像/custom/foobar/path/to/something?page=2
这样的请求将使用foobar
作为查找URL 的键和 proxy_pass
以及其余的路径和参数。
关于http - 如何在 nginx 中创建自定义位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36952909/
我是一名优秀的程序员,十分优秀!