Mastering Nginx: How Location Matching Order Impacts Performance
Understanding Nginx's location matching order is essential for efficient request handling, and this guide explains exact, longest-string, regex, prefix, and default matches with code examples and best-practice recommendations to optimize performance and reliability of your web server.
Nginx location matching order explained
The
locationdirective determines how Nginx processes incoming requests. Its matching order influences performance and correctness.
Exact match (=)
Chosen when the request URI exactly equals the string after
location. Highest priority.
<code>location = /favicon.ico {
# handle favicon.ico request
}</code>Longest‑string match (no modifier)
Selected when the request URI starts with the string after
locationand that string is the longest among candidates.
<code>location /images/ {
# handle requests beginning with /images/
}
location /images/jpg/ {
# handle requests beginning with /images/jpg/
}</code>Regular expression match (~ and ~*)
~ performs case‑sensitive regex matching, ~* performs case‑insensitive matching. Nginx checks regex locations in the order they appear.
<code>location ~ \.(gif|jpg|png)$ {
# handle .gif, .jpg, .png (case‑sensitive)
}
location ~* \.(GIF|JPG|PNG)$ {
# handle .GIF, .JPG, .PNG (case‑insensitive)
}</code>Prefix match (^~)
Matches a URI prefix when the following character is not “/”. It is evaluated after exact matches but before regex matches, effectively acting like a longest‑string match with higher priority.
<code>location ^~ /static/ {
# handle requests starting with /static/ (no further regex checks)
}</code>Default match (/)
If no other
locationblock matches, the default
location /block is used as a catch‑all.
<code>location / {
# handle all other requests
}</code>Summary and best practices
Prefer exact and longest‑string matches for static resources to improve performance.
Use regular expressions sparingly, especially on high‑traffic sites, due to their higher matching cost.
Place the default
location /block at the end of the configuration as a fallback.
Thoroughly test configuration changes to ensure correct request handling.
Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.