如何在nginx中IF语句中使用AND操作符?

oxosxuxt  于 2022-12-03  发布在  Nginx
关注(0)|答案(2)|浏览(198)

bounty将在7天后过期。回答此问题可获得+50声望奖励。Gill Bates希望奖励现有回答

我尝试根据响应头缓存请求。现在我希望的条件是,如果响应同时有2个头client-device和client-location,那么响应应该缓存在nginx端
所以我试着用这个代码

if ($http_client_device && $http_clocation) {
    set $cache_key "$request_uri$http_client_device$http_client_location";
}
proxy_cache_key $cache_key;

但是nginx不允许使用nginx:[emerg]在条件中出现意外的“&&”...
无论如何要为这一个工作?提前感谢

li9yvcax

li9yvcax1#

经过一整天的搜索,我找到了一个解决办法,参考这个主题http://rosslawley.co.uk/archive/old/2010/01/04/nginx-how-to-multiple-if-statements/
一般来说,我的代码看起来像这样:

if ($http_client_device) {
        set $temp_cache 1;
    }
    if ($http_client_location) {
        set $temp_cache 1$temp_cache;
    }
    if ($temp_cache = 11) {
        set $cache_key ...; 
    }

但是我仍然想知道在nginx中有没有更干净的方法来执行AND操作符

e0bqpujr

e0bqpujr2#

我使用以下语法

set $and 1;

if (<not condition>) {
    set $and 0;
}

if (<not condition>) {
    set $and 0;
}

if ($and) {
    # ...
}

例如:

if ($arg_a = 1 && $arg_b = 2) { ... }

可达到

set $ab 1

if ($arg_a != 1) {
    set $ab 0;
}

if ($arg_b != 2) {
    set $ab 0;
}

if ($ab) {
    # ...
}

参考:Nginx ifand
对于您的情况

set $set_cache_key 1;
if ($http_client_device = "") {
    set $set_cache_key 0;
}
if ($http_clocation = "") {
    set $set_cache_key 0;
}
if ($set_cache_key) {
    set $cache_key "$request_uri$http_client_device$http_client_location";
}
proxy_cache_key $cache_key;

相关问题