The only safe directives inside if in a location
The nginx documentation warns explicitly (“If Is Evil”): inside a location, only two statements behave predictably — return …; and rewrite … last; (Config anatomy). At the server level (outside location), if is safe.
Before and after
# Fragile: if inside location breaks try_files and header inheritance
location / {
if ($http_accept_language ~* ^ru) {
add_header X-Lang "ru";
}
try_files $uri $uri/ =404;
}
# Clean: compute in map (http context), no if inside location
map $http_accept_language $lang_hdr {
~*^ru "ru";
default "en";
}
server {
location / {
add_header X-Lang $lang_hdr always;
try_files $uri $uri/ =404;
}
}
If it doesn’t work
Adding if ($arg_v) { add_header … } inside a location broke try_files
- Cause
- The hidden
ifcontext took over request handling without inheritingtry_filesfrom the outerlocation. - Fix
- Compute the header value in a
mapblock at thehttplevel and pass the variable to a singleadd_headerwithoutif.
Two if blocks in a row inside a location behave unpredictably — only the last one takes effect
- Cause
- Each
ifcreates its own hidden context, and the last match replaces the settings from earlier ones. - Fix
- Combine conditions with
map(for example,map $a$b $result) at thehttplevel, and keep onlyif ($result) { return 403; }insidelocation.