Bird
Raised Fist0
Nginxdevops~10 mins

Preferential prefix match (^~) in Nginx - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Process Flow - Preferential prefix match (^~)
Request URL arrives
Check for exact match
Check for ^~ prefix matches
If ^~ prefix match found
Use this location block
If no ^~ prefix match
Check regex locations
Use best matching location
Nginx checks if the request URL matches any location with ^~ prefix first. If yes, it uses that location immediately, skipping regex checks.
Execution Sample
Nginx
location ^~ /images/ {
    # serve images
}

location ~* \.(gif|jpg|jpeg)$ {
    # regex match for images
}
This config prefers the prefix /images/ over regex matches for image files.
Process Table
StepRequest URLCheckMatch Found?Action Taken
1/images/logo.jpgExact match locationsNoContinue
2/images/logo.jpg^~ prefix locationsYes (/images/)Use /images/ location, skip regex
3/images/logo.jpgRegex locationsSkippedSkipped due to ^~ match
4/images/logo.jpgServe contentN/AContent served from /images/ location
5/pics/photo.gifExact match locationsNoContinue
6/pics/photo.gif^~ prefix locationsNoContinue
7/pics/photo.gifRegex locationsYes (\.(gif|jpg|jpeg)$)Use regex location
8/pics/photo.gifServe contentN/AContent served from regex location
9/docs/readme.txtExact match locationsNoContinue
10/docs/readme.txt^~ prefix locationsNoContinue
11/docs/readme.txtRegex locationsNoUse default location or 404
💡 Execution stops when a matching location is found or all checks fail.
Status Tracker
VariableStartAfter Step 2After Step 7After Step 11
Matched LocationNone/images//\.(gif|jpg|jpeg)$/None
Regex CheckedNoNo (skipped)YesYes
Content Served FromNone/images/ locationRegex locationDefault or 404
Key Moments - 3 Insights
Why does nginx skip regex checks when a ^~ prefix match is found?
Because ^~ means 'prefer this prefix match and do not check regex'. See execution_table row 2 where regex is skipped after ^~ match.
What happens if no ^~ prefix match is found?
Nginx continues to check regex locations and then default locations. See execution_table rows 6-11 for this flow.
Does ^~ match require the full URL to match the prefix?
No, it matches if the URL starts with the prefix. For example, /images/logo.jpg matches ^~ /images/ prefix (row 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does nginx decide to skip regex checks due to ^~ prefix match?
AStep 2
BStep 3
CStep 6
DStep 7
💡 Hint
Check the 'Match Found?' and 'Action Taken' columns at step 2 and 3.
According to variable_tracker, what is the matched location after step 7 for /pics/photo.gif?
A/images/
B/\.(gif|jpg|jpeg)$/
CNone
DDefault location
💡 Hint
Look at 'Matched Location' value after step 7 in variable_tracker.
If the URL is /docs/readme.txt, which location does nginx use according to execution_table?
A/images/ location
BRegex location
CDefault location or 404
D^~ prefix location
💡 Hint
Check steps 9-11 in execution_table for /docs/readme.txt.
Concept Snapshot
Nginx location matching order:
1. Exact match
2. ^~ prefix match (prefer this, skip regex)
3. Regex match
4. Default location
^~ means: if URL starts with prefix, use this location immediately.
Regex locations are skipped if ^~ prefix matches.
Full Transcript
When nginx receives a request URL, it first checks for exact location matches. If none found, it looks for any location blocks with the ^~ prefix that match the start of the URL. If a ^~ prefix match is found, nginx immediately uses that location and skips checking regex locations. If no ^~ prefix matches, nginx then checks regex locations. Finally, if no matches are found, nginx uses the default location or returns a 404. This behavior ensures that ^~ prefix matches have priority over regex matches, making prefix matching faster and more predictable.

Practice

(1/5)
1. What does the ^~ prefix in an nginx location block do?
easy
A. It tells nginx to prefer this prefix match and skip regex checks.
B. It makes nginx perform a case-insensitive match.
C. It enables regex matching for the location.
D. It disables all other location matches.

Solution

  1. Step 1: Understand nginx location matching

    nginx checks location blocks in order: exact, prefix, regex. The ^~ prefix tells nginx to prefer this prefix match and stop searching further.
  2. Step 2: Effect of ^~ prefix

    This means nginx will not check regex locations if this prefix matches, improving performance for static or specific URL prefixes.
  3. Final Answer:

    It tells nginx to prefer this prefix match and skip regex checks. -> Option A
  4. Quick Check:

    ^~ means prefer prefix and skip regex [OK]
Hint: Remember ^~ means prefer prefix, skip regex checks [OK]
Common Mistakes:
  • Confusing ^~ with regex (~ or ~*)
  • Thinking ^~ makes match case-insensitive
  • Assuming ^~ disables all other matches
2. Which of the following is the correct syntax to define a location block with preferential prefix match in nginx?
easy
A. location ~ /images/ { }
B. location ^~ /images/ { }
C. location ^ /images/ { }
D. location ~^ /images/ { }

Solution

  1. Step 1: Identify correct prefix syntax

    The preferential prefix match uses ^~ immediately after the word location.
  2. Step 2: Check each option

    location ^~ /images/ { } uses location ^~ /images/ { } which is correct. location ~^ /images/ { } mixes regex and prefix incorrectly. location ^ /images/ { } uses invalid ^ alone. location ~ /images/ { } uses regex ~ which is not preferential prefix.
  3. Final Answer:

    location ^~ /images/ { } -> Option B
  4. Quick Check:

    Correct syntax for preferential prefix = location ^~ [OK]
Hint: Look for 'location ^~' to define preferential prefix [OK]
Common Mistakes:
  • Using ~ or ~* instead of ^~ for prefix match
  • Placing ^~ after the path instead of after location
  • Omitting the space between ^~ and path
3. Given this nginx config snippet, which location block will handle the request for URL /static/css/style.css?
location /static/ {
  root /var/www/html;
}
location ^~ /static/css/ {
  root /var/www/css_files;
}
location ~* \.css$ {
  root /var/www/css_regex;
}
medium
A. The block with location /static/
B. The block with location ~* \.css$
C. No block matches; default server root is used
D. The block with location ^~ /static/css/

Solution

  1. Step 1: Identify matching locations for URL

    The URL /static/css/style.css matches all three locations: prefix /static/, preferential prefix ^~ /static/css/, and regex ~* \.css$.
  2. Step 2: Apply nginx matching order with ^~

    nginx prefers exact match first, then ^~ prefix matches, then regex. Since ^~ /static/css/ matches, nginx stops searching and uses this block.
  3. Final Answer:

    The block with location ^~ /static/css/ -> Option D
  4. Quick Check:

    ^~ prefix match stops regex checks [OK]
Hint: ^~ prefix match beats regex for matching URLs [OK]
Common Mistakes:
  • Choosing regex block because of file extension
  • Ignoring ^~ priority over regex
  • Assuming longest prefix always wins without ^~
4. You have this nginx config:
location ^~ /app/ {
  proxy_pass http://backend;
}
location ~ /app/secure/ {
  proxy_pass http://secure_backend;
}
But requests to /app/secure/login are handled by http://backend. What is the problem?
medium
A. The regex location syntax is incorrect and ignored.
B. The proxy_pass directive is missing a trailing slash.
C. The ^~ prefix match prevents regex location from being used.
D. nginx does not support mixing ^~ and regex locations.

Solution

  1. Step 1: Understand nginx location matching with ^~

    The ^~ prefix tells nginx to prefer this prefix match and skip regex checks if matched.
  2. Step 2: Analyze why regex location is ignored

    Since /app/secure/login matches ^~ /app/, nginx stops searching and uses that block, ignoring the regex location.
  3. Final Answer:

    The ^~ prefix match prevents regex location from being used. -> Option C
  4. Quick Check:

    ^~ stops regex location checks [OK]
Hint: ^~ disables regex locations if prefix matches [OK]
Common Mistakes:
  • Thinking regex overrides ^~ prefix
  • Believing proxy_pass syntax causes this issue
  • Assuming nginx can't mix ^~ and regex locations
5. You want nginx to serve static files from /var/www/static for URLs starting with /static/, and use regex locations for other patterns. Which config correctly uses ^~ to optimize performance?
hard
A. location ^~ /static/ { root /var/www/static; } location ~ \.php$ { fastcgi_pass unix:/run/php.sock; }
B. location /static/ { root /var/www/static; } location ^~ ~ \.php$ { fastcgi_pass unix:/run/php.sock; }
C. location ~ ^/static/ { root /var/www/static; } location ~ \.php$ { fastcgi_pass unix:/run/php.sock; }
D. location ~* /static/ { root /var/www/static; } location ^~ \.php$ { fastcgi_pass unix:/run/php.sock; }

Solution

  1. Step 1: Use ^~ for static file prefix

    To prioritize static files under /static/ and skip regex checks, use location ^~ /static/ { root /var/www/static; }.
  2. Step 2: Define regex location for PHP files

    Regex location for PHP files is defined with location ~ \.php$ { ... }. This will be checked only if ^~ prefix does not match.
  3. Step 3: Validate options

    location ^~ /static/ { root /var/www/static; } location ~ \.php$ { fastcgi_pass unix:/run/php.sock; } correctly uses ^~ prefix for static and regex for PHP. Other options misuse syntax or combine prefixes incorrectly.
  4. Final Answer:

    location ^~ /static/ { root /var/www/static; } with regex location for PHP -> Option A
  5. Quick Check:

    Use ^~ for static prefix, regex for others [OK]
Hint: Use ^~ for static prefixes, regex for patterns [OK]
Common Mistakes:
  • Mixing ^~ with regex in one location
  • Using regex (~) for static prefix
  • Incorrect syntax combining ^~ and regex