How do I DRY up this Nginx configuration?
Solution 1:
http {
map $cookie_no_cache $cacheZone {
default "";
true X;
}
server {
root /srv/web/example.com;
server_name example.com;
error_page 405 = @backend;
location / {
try_files /cache$cacheZone/$uri.html /static$cacheZone/$uri
/cache$cacheZone/$uri @backend;
}
location @backend {
proxy_pass http://localhost:8060;
}
}
}
Explanation.
- Regarding "no_cache" cookie check. We are replacing it with Nginx
map
. Variable$cacheZone
depends on the value of$cookie_no_cache
. By default it's empty, but if there is a "no_cache=true" cookie, we set$cacheZone
to any value to modify static file search path intry_files
-- I hope you have no/cacheX
and/staticX
folders under your server root (if yes, choose another value for$cacheZone
) - Nginx cannot apply HTTP methods
PUT
orPOST
to static files (this is meaningless), so that it issues HTTP error 405 "Not Allowed" in this case. We intercept it byerror_page
and pass the request to@backend
location.
Alternative approach
Otherwise, use proxy_cache
:
http {
proxy_cache_path example:1m;
server {
root /srv/web/example.com;
server_name example.com;
location / {
proxy_cache example;
proxy_cache_bypass $cookie_no_cache;
proxy_cache_valid 200 10s;
proxy_pass http://localhost:8060;
}
}
}