How is the prefix string location handling implemented within nginx?
Specifically, it's widely reported that the http://nginx.org/r/server_name matching is done through a hash table — http://nginx.org/docs/http/server_names.html — but there isn't a similar level of detail on the implementation of the location
directive.
The prefix-based
location
tree is defined to have 3 child node elements at each node:http://ngx.su/src/http/ngx_http_core_module.h#ngx_http_location_tree_node_s
This would appear to be a sort of a data-structure known as a prefix tree, or a trie:
https://en.wikipedia.org/wiki/Trie
To find the longest-matching
location
prefix string, in the presence of exact shorter-matching ones, nginx descends further into what it calls the inclusive match, into thetree
child element, keeping in mind the parts of the URI string that have already been matched; otherwise, the structure acts as a regular BST, where, depending on the result of the comparison operation of the URL against the current name of the node (performed by the likes of memcmp(3)), nginx descends either into the left or the right node of the sorted tree:http://ngx.su/src/http/ngx_http_core_module.c#ngx_http_core_find_static_location
An exact match (
location =
) results in somewhat of a special case of going into theright
tree, without a prefix optimisation:The tree is assembled by initially storing all location nodes in a queue, sorting the queue through insertion sort, and then assembling the prefix tree from the middle of the sorted queue:
http://ngx.su/src/http/ngx_http.c#ngx_http_block
http://ngx.su/src/http/ngx_http.c#ngx_http_init_locations
http://ngx.su/src/core/ngx_queue.c#ngx_queue_sort
http://ngx.su/src/http/ngx_http.c#ngx_http_init_static_location_trees
http://ngx.su/src/http/ngx_http.c#ngx_http_create_locations_tree