Nginx Location manual


 

Understanding Nginx Location block selection algorithm, Ngix webserver Location directive manual and Nginx Location priority.

General record of Nginx Location directive


 

The matching is performed against a normalized URI, after decoding the text encoded in the “%XX” form, resolving references to relative path components “.” and “..”, and possible compression of two or more adjacent slashes into a single slash.

Location can either be defined by a prefix string, or by a regular expression. Regular expressions are specified with the preceding ~* modifier (for case-insensitive matching), or the ~ modifier (for case-sensitive matching).

To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered. Then regular expressions are checked, in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used. If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used.

 

The search of regular expressions terminates on the first match, and the corresponding configuration is used.

 

Nginx Location directive priority and selection algorithm


 

  • nginx first checks locations defined using the prefix strings
  • location directives with the = prefix that match the query exactly. If found, searching stops.
  • All remaining directives with prefix strings. If this match used the ^~ prefix, searching stops.
  • location with the longest matching prefix is selected and remembered
  • then regular expressions are checked, in the order of their appearance in the configuration file
  • search of regular expressions terminates on the first match, and the corresponding configuration is used
  • if no match with a regular expression is found then the configuration of the prefix location remembered earlier is used

 

Another definition:

  1. Test the URI against all prefix strings.
  2. The = (equals sign) modifier defines an exact match of the URI and a prefix string. If the exact match is found, the search stops.
  3. If the ^~ (caret-tilde) modifier prepends the longest matching prefix string, the regular expressions are not checked.
  4. Store the longest matching prefix string.
  5. Test the URI against regular expressions.
  6. Break on the first matching regular expression and use the corresponding location.
  7. If no regular expression matches, use the location corresponding to the stored prefix string.

 

Example:

 

Pin It on Pinterest