Operations 6 min read

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.

Raymond Ops
Raymond Ops
Raymond Ops
Mastering Nginx: How Location Matching Order Impacts Performance

Nginx location matching order explained

The

location

directive 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

location

and 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

location

block 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.

performancenginxweb serverlocationrequest routing
Raymond Ops
Written by

Raymond Ops

Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.