What I want
I want to be able to set multiple nginx directives conditionally inside location blocks. For example, for a location /example, I want to set proxy_cache_revalidate on
if $http_method
is POST, otherwise I want to set proxy_cache_revalidate off
. I also want more directives like proxy_cache_valid
and add_header
to be set conditionally based on different variables like the remote ip, cookies, content type and more.
For a different location, these conditions must be able to look completely differently.
But why?
I don't know. I'm being paid to do this, there is a lot of money behind this and I don't have any say in these requirements. No sane person would want to implement this. Hopefully I will learn more about nginx along the way, though.
What I tried
My first idea was to use if
statements, but apparently those are evil and can not be used inside location blocks in the way I wanted. If it was doable, I would have written something like this:
http {
[...]
server {
[...]
location /example {
[...]
if ($http_method = "POST") {
proxy_cache_revalidate on;
}
else { # yeah okay, there is no else-statement anyway, but you get the point...
proxy_cache_revalidate off;
}
}
}
}
Then I thought I might be able to work around that using maps. Those can't be used in location blocks either, so things would get messy, but potentially doable. I would have to create lots and lots of maps, a couple of them per location block.
But it turns out this doesn't work either:
http {
[...]
map $http_method $foo {
POST on;
default off;
}
server {
[...]
location /example {
[...]
proxy_cache_revalidate $foo;
}
}
}
nginx: [emerg] invalid value "$foo" in "proxy_cache_revalidate" directive, it must be "on" or "off" in /etc/nginx/nginx.conf:251
It seems like nginx really isn't built for this. I can't find much information on the internet either. Is there any workaround or more reasonable approach that I can use?