Nginx giving priority to nested location over outer location block

nginx

Can someone shed some light on why this doesn't work the way one would expect it to?
In the following nginx configuration, the assumption is that the first nginx will go with the regex-matching image extensions block, and only afterwards would it enter the inner block where the ^~ takes preference over everything else.

It seems nginx is looking at the bigger picture regardless of scope, and matching ^~ /images before the outer regex extension block for a request like /images/something.png?

location ~* \.(css|js|jpg|png|gif|ico)$ {
    expires 7d;
    add_header Image-By-Extension 1;
}

location / {
    location ^~ /images {
        add_header Image-By-Folder 1;
        ...
    }
}

Best Answer

Yes nginx has to choose one location so it won't report the matching later even if you are nesting these. When you use ~^ operator you tell nginx to avoid looking at regex location blocks if it's the longest prefixed location block matching the current request URI.

I explained the whole process here : Nginx rewite rules 403 error.