basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    if inside location — keep only return or rewrite, move everything else to map

    Inside a location, if behaves like a hidden nested location rather than a conditional, dropping try_files, headers, and proxy settings. Use map in the http context for branching.

    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 if context took over request handling without inheriting try_files from the outer location.
    Fix
    Compute the header value in a map block at the http level and pass the variable to a single add_header without if.

    Two if blocks in a row inside a location behave unpredictably — only the last one takes effect

    Cause
    Each if creates 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 the http level, and keep only if ($result) { return 403; } inside location.