Nginx location priority

In Nginx website, it includes these docs as the following:

Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }  
        location @name { ... }
Default: —  
Context: server, location  

A location can either be defined by a prefix string, or by a regular expression. Location blocks can be nested, with some exceptions mentioned above.

Let's explain something about this:

  1. The exact match is the first priority.
  2. The prefix match is the second priority, but there are two type prefix matches like ^~ and /, if we use ^~, nginx will skip all the regular matches.

A little fake code as the following:

def match(uri):  
    rv = NULL

    if uri in exact_match:
        return exact_match[uri]

    if uri in prefix_match:
        if prefix_match[uri] is '^~':
            return prefix_match[uri]
        else:
            rv = prefix_match[uri]

    if uri in regex_match:
        return regex_match[uri]

    return rv

Let’s illustrate the above by an example:

location  = / {  
    # matches the query / only.
    [ configuration A ] 
}

location  / {  
    # matches any query, since all queries begin with /, but regular
    # expressions and any longer conventional blocks will be
    # matched first.
    [ configuration B ] 
}

location /documents/ {  
    # matches any query beginning with /documents/ and continues searching,
    # so regular expressions will be checked. This will be matched only if
    # regular expressions don't find a match.
    [ configuration C ] 
}

location ^~ /images/ {  
    # matches any query beginning with /images/ and halts searching,
    # so regular expressions will not be checked.
    [ configuration D ] 
}

location ~* \.(gif|jpg|jpeg)$ {  
    # matches any request ending in gif, jpg, or jpeg. However, all
    # requests to the /images/ directory will be handled by
    # Configuration D.   
    [ configuration E ] 
}
  • If we are requesting /index.html, it will match configureation B.
  • If we are requesting /foo.jpg, it will find configuration B at first, then regular match configuration E finally.
  • If we are requesting /images/foo, it will match configuration D, but never match regular location becasuse of ^~