Nginx config goal:
- Check if a certain cookie exists (doesn't matter what the value is)
- If it doesn't exist, include a particular config import.
- I only want to apply my rules to certain Locations, I cannot apply these conditionals to the global nginx configs. It's location specific.
CURRENTLY, the config looks like this, and it's working well:
location ~ ^/somedestination\.php(/|$) {
<... truncated other config lines for readability ...>
include includes/xx-cache-config.conf;
<... truncated other config lines for readability ...>
fastcgi_pass php-fpm:9000;
}
This server has many location blocks, and each import
their own cache configs. This is a cgi only application, there is no direct try_files here.
So, in order to meet the above goals, I am experimenting with something like this, checking for existence of $cookie_user
variable, and only applying my config if the cooke doesn't exist:
location ~ ^/somedestination\.php(/|$) {
# only include cache config if the cookie is null/empty
if ($cookie_user = false) {
include includes/xx-cache-config.conf;
}
fastcgi_pass php-fpm:9000;
}
Seems logical, but here's the problem: I stumbled on this: https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/
QUESTION: If we shouldn't use if
in a Location context (according to nginx official docs), how should I be doing this?
EDIT: Here is the contents of what's being included from the conditional clause. Currently nginx is ALWAYS including this config, my goal right now is to sometimes not include it (when the cookie exists).
Note: zone config itself is included elsewhere. This included config enables it.
includes/xx-cache-config.conf
fastcgi_cache CACHE_TLRS;
fastcgi_cache_bypass $no_resource_cache;
fastcgi_no_cache $no_resource_cache;
fastcgi_cache_valid 200 301 48h;
fastcgi_cache_valid 302 4h;
fastcgi_cache_revalidate on;
fastcgi_cache_use_stale http_500 http_503 timeout updating;
fastcgi_cache_lock on;
fastcgi_cache_lock_age 15s;
fastcgi_cache_lock_timeout 5s;
fastcgi_ignore_headers cache-control;
fastcgi_cache_key "$scheme$host$uri";
add_header X-Cache $upstream_cache_status;
I was overthinking this.
After doing some reading, it seems imports are evaluated at server start, so you can't put them in a conditional.
So, I ended up utilizing the
fastcgi_cache_bypass
directive, I accomplished the goal without usingif
at all.Modified the existing line
fastcgi_cache_bypass $no_resource_cache;
Changed it to:
fastcgi_cache_bypass $cookie_user $no_resource_cache;
This will bypass cache if the variable(s) is not empty and not "0"
Doc link: http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache_bypass