Ho do I conditionally remove a subset of try_files directives in Nginx?

I’m trying to conditionally remove a subset of try_files directives to bypass static HTML caches when a custom header X-No-Cache is present.

Here is in theory what I'm trying to do:

location @wp {
  try_files $uri $uri/ /index.php?$query_string;
}

location / {
  if ($http_x_no_cache) {
    @wp;
  }
  try_files /cache$request_uri.html /cache$request_uri/index.html $uri $uri/ /index.php?$query_string;
}

The reason behind this is so logged in website users can send requests with the X-No-Cache header and bypass the static cache.


If you want to prevent caching for non-logged users, you should check the value of WordPress login cookie. Then you don't need to set those headers.

This configuration could produce the results you are looking for:

http {
    map $http_cookie $cachefiles {
        default "/cache/$request_uri.html /cache$request_uri/index.html";
        "~.*wordpress_logged_in.*" "";
    }
    server {
        try_files $cachefiles $uri $uri/ /index.php?$query_string;
    }
}

I was able to get this working as expected. You can not use spaces within the map directive. So, to solve this I had to remove the extra try files location. I had to update my backend so I no longer needed to look in multiple locations.

map $http_cookie $cachefiles {
    default "/cache/$new_request_uri.html";
    "~*wordpress_logged_in" "";
}

server {
    ....
    
    set $new_request_uri $request_uri;
    
    # parse URL and remove ending and trailing slashes
    if ($request_uri ~ ^\/(.*)\/$) {
        set $new_request_uri $1;
    }
    
    # if root then use index
    if ($request_uri ~ ^\/$) {
        set $new_request_uri index;
    }

    .....
    
    location / {
        try_files $cachefiles $uri $uri/ /index.php?$query_string;
    }

    ....
}