如何解决如何让nginx重定向到url编码的查询参数
我需要对通过查询参数传递的 url 进行代理调用,例如:
我的 nginx 代理部署在:https://myproxy.net
如果重定向参数不是 url 编码的,我可以使用这个块进行调用:
location /basepath {
if ( $arg_redirect = '') {
return 400 "Missing redirect directive in request";
}
proxy_pass $arg_redirect;
proxy_intercept_errors on;
error_page 301 302 307 = @handle_redirects;
}
错误拦截和@handle_redirects 然后处理可能在新目的地弹出的其他 30X 代码。
这适用于请求:GET
:https://myproxy.net/basepath?redirect=https://destination.com/somepath/uuid
我需要做什么才能使它适用于:GET
:https://myproxy.net/basepath?redirect=https%3A%2F%2Fdestination.com%2Fsomepath%2Fuuid
此外,作为规范的一部分,它必须是纯 nginx,而不是其他模块、lua 等。 谢谢!
解决方法
实际上,proxy_pass
是默认做归一化的,但它只影响 $uri
部分。因此,您只需要解码传递字符串的开头即可使其正常工作:
location / {
if ( $arg_redirect = '') {
return 400 "Missing redirect directive in request";
}
if ( $arg_redirect ~ (.+)%3A%2F%2F(.+) ){ # fix :// between scheme and destination
set $arg_redirect $1://$2;
}
if ( $arg_redirect ~ (.+?)%3A(.*) ){ # fix : between destination and port
set $arg_redirect $1:$2;
}
if ( $arg_redirect ~ (.+?)%2F(.*) ){ # fix / after port,the rest will be decoded by proxy_pass
set $arg_redirect $1/$2;
}
proxy_pass $arg_redirect;
}
通过上述,我设法访问了 http://localhost/?redirect=http%3A%2F%2F127.0.0.1%3A81%2Fsfoo%20something%2Fs
解决方案看起来很脏,使用默认模块的唯一替代方法是 map
(在我看来甚至更不干净)。我宁愿将 redirect
参数拆分为多个部分:方案(http 或 https)、目的地、端口和 uri。有了它,您就可以在不重写的情况下构建完整地址:
proxy_pass $arg_scheme://$arg_dest:$arg_port/$arg_uri
,
好的,有一个非常奇怪和好奇的解决方案
server {
listen 80;
resolver x.x.x.x;
location /basepath {
if ($arg_redirect = '') {
return 400 "Missing redirect directive in request";
}
proxy_pass http://127.0.0.1:80/basepath/$arg_redirect;
}
location ~ ^/basepath/(?<proto>\w+):/(?<redir>.+)$ {
proxy_pass $proto://$redir;
}
}
Nginx 不会使用 proxy_pass 中的变量对路径进行编码并按原样发送。因此,我将 $arg_* 作为 proxy_pass uri 的一部分,向 self 发送请求,nginx 将收到将被解码的新请求。
但是因为 Nginx 会清理路径并将 //
替换为 /
,所以我在正则表达式中拆分了协议部分。
而且......我永远不会推荐使用这个解决方案,但它有效:)
,试试这个,让我知道它是否有效
location /basepath {
if ( $arg_redirect = '') {
return 400 "Missing redirect directive in request";
}
set_unescape_uri $decodedredirect $arg_redirect;
proxy_pass $decodedredirect;
proxy_intercept_errors on;
error_page 301 302 307 = @handle_redirects;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。