Why is my Nginx location rule not taking precedence?

Solution 1:

Maybe because of the prefix match (^~) on the location block and nginx is skipping the regex check:

If the longest matching prefix location has the “^~” modifier then regular expressions are not checked

Try removing the prefix check i.e:

location /_links/ { 
Regex here 
}

Also remove the root declaration inside the location /_links/ block you don't need it, see nginx pitfalls for more information, basically servers root declaration is used then location is matched $root/$location

Also as suggested above have a look at the try_files directive instead of the if(condition){match}

I.e. instead of:

if (!-f $request_filename) {
    rewrite ^/(.*)$ /index.php?q=$1 last;
}

A better solution would be:

try_files $uri $uri/ /index.php?q=$uri;

This is also mentioned in the nginx pitfalls wiki page.