测试参数是否存在并在 nginx 中处理 proxy_pass

Test if parameter exists and handle proxy_pass in nginx

我想检查 url 中是否存在名为“token”的参数并且不为空。根据测试结果,我想 redirect 或使用 proxy_pass.

示例:

我当前的会议:[​​=21=]

location /application/foo {
    if ($arg_token) {
        proxy_pass http://127.0.0.1:8512/application/foo;
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 86400;
    }

    return 302 https://example.com/?application=foo&$args;
}

但是returns出现以下错误:

nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block

我已检查 上述错误,但它解释了 location 指令而非 if 指令的行为。

我尝试使用 negation of the if test 但无法做出所需的行为或没有错误。我也知道 ifs 在 nginx 中是邪恶的,但我对 nginx 的了解还不够多,无法以不同的方式做我想做的事。

location 中的 if 最好限制为执行 returnrewrite 语句,如 advised here.

在 Nginx 中,未定义或空参数的计算结果都是空字符串,因此您可以使用 = "" 反转 if 语句的逻辑。因此,将 return 语句移到块内,将 proxy_pass 语句移到块外。

例如:

location /application/foo {
    if ($arg_token = "") {
        return 302 https://example.com/?application=foo&$args;
    }
    proxy_pass ...;
    ...
}