Nginx – How to Use Different try_files Based on Query Parameter

nginx

location / {
    try_files "/wp-content/cache/all/${uri}index.html" $uri $uri/ /index.php?q=$uri&$args;
}

But if there is a visual editor used, I don't want to use the cache. So it should be

location / {
    if ($args ~ visual-editor){
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }
    try_files "/wp-content/cache/all/${uri}index.html" $uri $uri/ /index.php?q=$uri&$args;
}

Except it doesn't work because nginx is restrictive and weird to someone who mostly did apache configs.

I tried named locations, I tried a sub location to make it happy about using try_files, I don't want a rewrite, using the error code hack with named locations will cause query parameters to be removed which can't happen.

The idea is simple, don't load the cached html file if there's some exclusion I define. But nothing seems to work and the internet gives answers that never answer my question so asking here.

Best Answer

You cannot put try_files into an if block, but you can set a variable in the if block and use that to invalidate the first term of the try_files statement.

For example:

server {
    ...
    set $cache /wp-content/cache/all;
    if ($args ~ visual-editor) { set $cache /nonexistent; }

    location / {
        try_files $cache${uri}index.html $uri $uri/ /index.php?q=$uri&$args;
    }
    ...
}

See this caution on the use of if.