Bird
Raised Fist0
Nginxdevops~5 mins

Preferential prefix match (^~) in Nginx - Commands & Configuration

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
Introduction
Sometimes you want nginx to match a URL prefix exactly and stop searching for other matches. The ^~ prefix tells nginx to use this location if the URL starts with the given prefix, ignoring regex locations. This helps serve specific paths faster and more predictably.
When you want to serve static files from a specific folder without regex slowing down matching.
When you have a URL prefix that should always use a certain configuration, ignoring regex rules.
When you want to improve performance by avoiding regex checks for common URL prefixes.
When you want to make sure a certain path is handled by a specific location block without surprises.
When you want to simplify URL routing by prioritizing prefix matches over regex matches.
Config File - nginx.conf
nginx.conf
server {
    listen 80;
    server_name example.com;

    location ^~ /images/ {
        root /var/www/static;
        # This serves all requests starting with /images/ from /var/www/static/images/
    }

    location ~* \.(jpg|jpeg|png|gif)$ {
        # Regex location for image files
        expires 30d;
    }

    location / {
        proxy_pass http://localhost:3000;
    }
}

The location ^~ /images/ block tells nginx to use this block for any URL starting with /images/ and stop searching further, ignoring regex locations.

The location ~* \.(jpg|jpeg|png|gif)$ block is a regex match for image files, but it will be ignored if the URL starts with /images/ because of the ^~ prefix.

The location / block is the default catch-all for other requests.

Commands
Check the nginx configuration file syntax to make sure there are no errors before reloading.
Terminal
sudo nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Reload nginx to apply the new configuration without stopping the server.
Terminal
sudo systemctl reload nginx
Expected OutputExpected
No output (command runs silently)
Send a request to check headers for a file under /images/ to confirm the ^~ prefix location is used.
Terminal
curl -I http://example.com/images/logo.png
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Content-Type: image/png Content-Length: 12345 Last-Modified: Wed, 01 Jan 2020 12:00:00 GMT Connection: keep-alive
Send a request for an image file outside /images/ to confirm regex location is used for caching headers.
Terminal
curl -I http://example.com/picture.jpg
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Content-Type: image/jpeg Expires: Thu, 01 Aug 2024 12:00:00 GMT Cache-Control: max-age=2592000 Connection: keep-alive
Key Concept

If you remember nothing else from this pattern, remember: the ^~ prefix tells nginx to use this location block for matching URL prefixes and skip regex checks.

Common Mistakes
Using regex location (~) before a ^~ prefix location for the same URL prefix.
nginx will ignore the regex location if a ^~ prefix location matches first, causing unexpected behavior.
Use ^~ for prefix matches you want to prioritize and avoid conflicting regex locations for the same prefix.
Not testing nginx configuration before reload.
Syntax errors can cause nginx to fail to reload, leading to downtime.
Always run 'nginx -t' to verify configuration syntax before reloading.
Summary
Use the ^~ prefix in nginx location blocks to prioritize prefix matches over regex matches.
Test nginx configuration syntax with 'nginx -t' before reloading to avoid errors.
Reload nginx with 'systemctl reload nginx' to apply changes without downtime.
Verify location matching by sending HTTP requests to URLs under the prefix and outside it.

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