问题很简单,假设我在 nginx 中有一个变量:
set $test $upstream_status;
现在变量中的状态将是例如“200”。我如何将此变量转换为数字以便像这样使用它:
return $test "test";
回答1
每个 nginx 变量都是一个字符串,唯一的例外是 https://nginx.org/en/docs/http/ngx_http_core_module.html#var_binary_remote_addr 一个(毕竟它仍然是一个 4 或 16 字节长度的二进制压缩字符串)和其他一些。然而,并非每个 nginx 指令都允许您使用变量来指定其参数,而 return
指令的 HTTP 返回代码正是其中一种情况。
此外,无论你想做什么,你肯定会以错误的方式去做。 https://nginx.org/en/docs/http/ngx_http_rewrite_module.html 模块(包括 return
模块)中的所有指令都在请求处理的早期阶段执行,在任何东西被发送到上游之前,甚至没有谈论什么应该收到。通常这样的事情可以使用 proxy_intercept_errors on;
设置并为特定上游返回代码指定一个 https://nginx.org/en/docs/http/ngx_http_core_module.html#error_page 处理程序来实现,例如
location / {
proxy_pass ...
proxy_intercept_errors on;
error_page 301 @handler_301;
error_page 302 @handler_302;
...
}
location @handler_301 {
# you are free to use 'return 301 "anything"' here
...
}
location @handler_302 {
...
}
...
但是,您可以拦截的唯一返回代码是 300 及以上。