Bird
Raised Fist0
Nginxdevops~5 mins

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 your web server to respond differently based on the beginning part of a website address. Prefix match lets you do this by checking if a URL starts with a certain path and then applying special rules for it.
When you want to serve different content for URLs starting with /images versus other URLs.
When you want to redirect all URLs starting with /blog to a new location.
When you want to apply security rules only to URLs starting with /admin.
When you want to cache all requests starting with /static differently.
When you want to proxy requests starting with /api to a backend server.
Config File - nginx.conf
nginx.conf
events {}
http {
    server {
        listen 80;
        server_name example.com;

        location /images/ {
            root /var/www;
        }

        location /blog/ {
            return 301 https://blog.example.com$request_uri;
        }

        location /admin/ {
            auth_basic "Restricted Area";
            auth_basic_user_file /etc/nginx/.htpasswd;
        }

        location / {
            root /var/www/html;
        }
    }
}

This configuration sets up an Nginx server listening on port 80 for example.com.

The location /images/ block matches any URL starting with /images/ and serves files from /var/www/images.

The location /blog/ block matches URLs starting with /blog/ and redirects them to a new blog domain.

The location /admin/ block matches URLs starting with /admin/ and requires a password to access.

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

Commands
Check the Nginx configuration file for syntax errors before applying it.
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)
Test that a URL starting with /images/ serves the correct content.
Terminal
curl -I http://example.com/images/logo.png
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Content-Type: image/png ...
Test that a URL starting with /blog/ redirects to the new blog domain.
Terminal
curl -I http://example.com/blog/post1
Expected OutputExpected
HTTP/1.1 301 Moved Permanently Location: https://blog.example.com/blog/post1 Server: nginx ...
Test that a URL starting with /admin/ requires authentication.
Terminal
curl -I http://example.com/admin/dashboard
Expected OutputExpected
HTTP/1.1 401 Unauthorized WWW-Authenticate: Basic realm="Restricted Area" Server: nginx ...
Key Concept

If you remember nothing else from this pattern, remember: Nginx matches URLs by checking if they start with the prefix you specify in the location block.

Common Mistakes
Using location blocks without trailing slashes for prefix matching.
Nginx treats location without trailing slash differently, which can cause unexpected matches or misses.
Always include the trailing slash in the location prefix when you want to match URL beginnings, like /images/.
Placing a more general location block before a more specific one.
Nginx uses the longest prefix match, but order can affect regex locations; general blocks may override specific ones if misconfigured.
Put specific prefix location blocks before general ones and avoid regex conflicts.
Summary
Use location blocks with a trailing slash to match URL prefixes in Nginx.
Test your configuration with 'nginx -t' before reloading to avoid errors.
Reload Nginx to apply changes without downtime.
Use curl commands to verify that prefix matches behave as expected.

Practice

(1/5)
1. What does prefix match in nginx do when routing requests?
easy
A. It matches requests based on the start of the URL path.
B. It matches requests only if the full URL matches exactly.
C. It matches requests based on the file extension.
D. It matches requests randomly to any location block.

Solution

  1. Step 1: Understand prefix match concept

    Prefix match means nginx checks if the URL path starts with a specific string.
  2. Step 2: Compare with other matching types

    Exact match requires full URL match, file extension match is unrelated, random match is invalid.
  3. Final Answer:

    It matches requests based on the start of the URL path. -> Option A
  4. Quick Check:

    Prefix match = start of URL path [OK]
Hint: Prefix match checks URL start, not full or random [OK]
Common Mistakes:
  • Confusing prefix match with exact match
  • Thinking prefix match checks file extensions
  • Assuming prefix match is random
2. Which of the following is the correct syntax for a prefix match location in nginx?
easy
A. location = /images/ { }
B. location ^~ /images/ { }
C. location /images/ { }
D. location ~ /images/ { }

Solution

  1. Step 1: Identify prefix match syntax

    Prefix match uses plain location /prefix/ { } without modifiers.
  2. Step 2: Understand other modifiers

    = is exact match, ^~ is prefix but with higher priority, ~ is regex match.
  3. Final Answer:

    location /images/ { } -> Option C
  4. Quick Check:

    Plain location = prefix match [OK]
Hint: Plain location block means prefix match [OK]
Common Mistakes:
  • Using = or ^~ modifiers for simple prefix match
  • Confusing regex (~) with prefix match
  • Missing trailing slash in prefix
3. Given this nginx config snippet:
location /app/ {
  proxy_pass http://backend1;
}
location /app/api/ {
  proxy_pass http://backend2;
}

Which backend will handle a request to /app/api/users?
medium
A. Both backends in round-robin
B. http://backend2
C. No backend, 404 error
D. http://backend1

Solution

  1. Step 1: Understand prefix match selection

    nginx selects the location with the longest matching prefix for plain prefix locations (no modifiers).
  2. Step 2: Compare prefixes

    Both /app/ (length 5) and /app/api/ (length 9) match /app/api/users, but /app/api/ is longer, so it wins.
  3. Final Answer:

    http://backend2 -> Option B
  4. Quick Check:

    Longest prefix wins [OK]
Hint: Longest matching prefix wins [OK]
Common Mistakes:
  • Thinking config order (first match) wins instead of longest prefix
  • Thinking regex or exact match applies here
  • Believing nginx load balances both backends
4. You wrote this nginx config:
location /static {
  root /var/www/html;
}

Requests to /static/css/style.css return 404. What is the likely error?
medium
A. root directive path is incorrect
B. location block should use = modifier
C. Missing trailing slash in location prefix
D. proxy_pass is missing

Solution

  1. Step 1: Understand root directive behavior

    root appends the full request URI (/static/css/style.css) to /var/www/html, looking for /var/www/html/static/css/style.css.
  2. Step 2: Identify likely cause

    If static files are at /var/www/html/css/style.css (without static/), root path doesn't strip prefix, causing 404. (Use alias /var/www/html; to strip.)
  3. Final Answer:

    root directive path is incorrect -> Option A
  4. Quick Check:

    root + full URI (no prefix strip) [OK]
Hint: root appends full URI; alias strips prefix [OK]
Common Mistakes:
  • Confusing root (full URI) with alias (strips prefix)
  • Thinking trailing slash strips prefix for root
  • Adding unnecessary modifiers like =
5. You want nginx to route all requests starting with /api/ to http://backend_api and all others to http://backend_web, ensuring the /api/ prefix has priority even if regex locations follow. Which config correctly uses prefix match for this?
hard
A. location ~ /api/ { proxy_pass http://backend_api; } location / { proxy_pass http://backend_web; }
B. location /api/ { proxy_pass http://backend_api; } location / { proxy_pass http://backend_web; }
C. location = /api/ { proxy_pass http://backend_api; } location / { proxy_pass http://backend_web; }
D. location ^~ /api/ { proxy_pass http://backend_api; } location / { proxy_pass http://backend_web; }

Solution

  1. Step 1: Use ^~ for prefix priority

    The ^~ modifier tells nginx to stop searching if prefix matches, ensuring /api/ routes to backend_api even over later regex.
  2. Step 2: Default location for others

    The plain location / { } catches all other requests to backend_web.
  3. Final Answer:

    location ^~ /api/ { proxy_pass http://backend_api; } location / { proxy_pass http://backend_web; } -> Option D
  4. Quick Check:

    ^~ prefix match for priority routing [OK]
Hint: Use ^~ to prioritize prefix match over regex [OK]
Common Mistakes:
  • Not using ^~ causes regex or exact match to override
  • Using = modifier limits to exact /api/ only
  • Using ~ makes it regex, not prefix match