Process Flow - Prefix match
Request URL arrives
Check location blocks
Match prefix location?
Serve content or proxy
Nginx checks the request URL against location blocks using prefix matching to find the best matching path prefix.
Jump into concepts and practice - no test required
location /images/ {
root /data;
}
location / {
root /var/www/html;
}| Step | Request URL | Location Tested | Prefix Match? | Action Taken |
|---|---|---|---|---|
| 1 | /images/cat.png | /images/ | Yes | Select this location |
| 2 | /images/cat.png | / | Yes | Keep searching for longer prefix |
| 3 | /images/cat.png | No more locations | N/A | Serve from /images/ location root /data |
| 4 | /about.html | /images/ | No | Skip this location |
| 5 | /about.html | / | Yes | Select this location |
| 6 | /about.html | No more locations | N/A | Serve from / location root /var/www/html |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| Selected Location | None | /images/ | /images/ | /images/ | /images/ |
| Request URL | /images/cat.png | /images/cat.png | /images/cat.png | /images/cat.png | /images/cat.png |
Nginx prefix match: - Checks request URL against location prefixes - Chooses longest matching prefix - If none match, uses default location - Example: /images/ matches URLs starting with /images/ - Order matters only for regex, prefix matches longest prefix wins
location /prefix/ { } without modifiers.= is exact match, ^~ is prefix but with higher priority, ~ is regex match.location /app/ {
proxy_pass http://backend1;
}
location /app/api/ {
proxy_pass http://backend2;
}/app/api/users?/app/ (length 5) and /app/api/ (length 9) match /app/api/users, but /app/api/ is longer, so it wins.location /static {
root /var/www/html;
}/static/css/style.css return 404. What is the likely error?root appends the full request URI (/static/css/style.css) to /var/www/html, looking for /var/www/html/static/css/style.css./var/www/html/css/style.css (without static/), root path doesn't strip prefix, causing 404. (Use alias /var/www/html; to strip.)/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?^~ modifier tells nginx to stop searching if prefix matches, ensuring /api/ routes to backend_api even over later regex.location / { } catches all other requests to backend_web.