我应该如何配置 Nginx 以代理到参数传递的 URL?
How should I configure Nginx to proxy to a URL passed by parameter?
我正在尝试访问 OAuth2 身份验证后的媒体文件(图像、视频)。
为了访问资源,我需要向请求中添加一个自定义的 Authorization Bearer 令牌,所以我不能使用简单的重写(嗯,至少据我所知)。
它不能通过普通 HTML(比如 img
或 video
标签)完成,所以我正在考虑让 Nginx 将查询代理到最终服务器。
每个媒体资源都将通过 /proxy
路径加载,带有 token
参数(用于身份验证)和 url
用于加载实际资源。
样本URL:
http://myserver.com/proxy/?token=12345&url=http://protectedserver.com/custompath/asset
这是我想出的,但我不太确定如何配置 proxy_pass
指令,因为我需要它专门代理到 $url
变量。我不需要代理路径(无论如何它都是空的)。
location /proxy/ {
if ($arg_token ~ "^$") { return 404; }
if ($arg_url ~ "^$") { return 404; }
set $url $arg_url;
proxy_set_header Authorization "Bearer $arg_token";
set $args "";
#proxy_pass $url;
}
注意:这将是 运行 在一个封闭的环境中,只有特定的机器(交互受限的信息亭)才能访问该页面,所以我不担心授权令牌的潜在泄漏。
我在 ServerFault 上注意到一个类似的问题,但没有人回答:
https://serverfault.com/questions/671991/nginx-proxy-pass-url-from-get-argument
我正在寻找使其正常工作的配置设置或可行的替代解决方案。
这是针对我的问题的正确配置:
location /proxy/ {
if ($arg_token ~ "^$") { return 404; }
if ($arg_url ~ "^$") { return 404; }
set $url $arg_url;
set $token $arg_token;
set $args "";
# IMPORTANT, this is required when using dynamic proxy pass
# You can alternatively use any DNS resolver under your control
resolver 8.8.8.8;
proxy_pass $url;
proxy_set_header Authorization "Bearer $token";
proxy_redirect off;
}
我正在尝试访问 OAuth2 身份验证后的媒体文件(图像、视频)。
为了访问资源,我需要向请求中添加一个自定义的 Authorization Bearer 令牌,所以我不能使用简单的重写(嗯,至少据我所知)。
它不能通过普通 HTML(比如 img
或 video
标签)完成,所以我正在考虑让 Nginx 将查询代理到最终服务器。
每个媒体资源都将通过 /proxy
路径加载,带有 token
参数(用于身份验证)和 url
用于加载实际资源。
样本URL:
http://myserver.com/proxy/?token=12345&url=http://protectedserver.com/custompath/asset
这是我想出的,但我不太确定如何配置 proxy_pass
指令,因为我需要它专门代理到 $url
变量。我不需要代理路径(无论如何它都是空的)。
location /proxy/ {
if ($arg_token ~ "^$") { return 404; }
if ($arg_url ~ "^$") { return 404; }
set $url $arg_url;
proxy_set_header Authorization "Bearer $arg_token";
set $args "";
#proxy_pass $url;
}
注意:这将是 运行 在一个封闭的环境中,只有特定的机器(交互受限的信息亭)才能访问该页面,所以我不担心授权令牌的潜在泄漏。
我在 ServerFault 上注意到一个类似的问题,但没有人回答: https://serverfault.com/questions/671991/nginx-proxy-pass-url-from-get-argument
我正在寻找使其正常工作的配置设置或可行的替代解决方案。
这是针对我的问题的正确配置:
location /proxy/ {
if ($arg_token ~ "^$") { return 404; }
if ($arg_url ~ "^$") { return 404; }
set $url $arg_url;
set $token $arg_token;
set $args "";
# IMPORTANT, this is required when using dynamic proxy pass
# You can alternatively use any DNS resolver under your control
resolver 8.8.8.8;
proxy_pass $url;
proxy_set_header Authorization "Bearer $token";
proxy_redirect off;
}