ii. Location Selection Algorithm
Generally, the selection algorithm works as follows:
Matching Processing Sequence Similar to how it chooses a server block, Nginx chooses the location that will be used to serve a request. It goes through a procedure that decides which location block is the most appropriate for any given request. It's essential to comprehend this procedure in order to configure Nginx effectively and reliably.
Nginx assesses the potential location contexts by comparing the request URI to each of the locations while keeping in mind the different location declaration types we discussed earlier here i. Nginx Location Directive. It accomplishes this using the following algorithm:
All prefix-based location matches (location types without regular expressions) are first verified by Nginx. It compares each location to the entire request URI.
Nginx starts by searching for an exact match. The location block that matches the request URI exactly and has the =
modifier is chosen right away to fulfill the request.
Nginx evaluates non-exact prefixes if no exact (with the = modifier) location block matches are discovered. It locates the request URI's longest matched prefix location and evaluates it as follows:
c.1 If the longest matching prefix location includes the modifier ^~
, Nginx will stop looking for it right away and choose it to fulfill the request.
c.2 If the longest matching prefix location does not employ the modifier ^~
, Nginx saves the match for the time being so that the search focus can be switched.
After determining and storing the longest matching prefix location, Nginx proceeds to evaluate the regular expression locations (both case sensitive and insensitive). If there are any regular expression locations within the longest matching prefix location, Nginx will bring those to the top of its list of regex locations to check. Nginx then attempts to match the regular expression places sequentially. The first regular expression location that matches the request URI is chosen to serve the request.
The previously saved prefix location is chosen to serve the request if no regular expression locations matching the request URI are discovered.