NGINX uses location blocks to route requests. Which statement best explains how NGINX chooses the correct location block?
Think about how NGINX tries to find the most specific match for a request URI.
NGINX uses a specific order to match location blocks. It first looks for exact matches, then prefix matches with the longest prefix, and finally regex matches. This ensures the most specific location handles the request.
Given this NGINX config snippet:
server {
listen 80;
location /app/ {
proxy_pass http://backend1;
}
location /app/v2/ {
proxy_pass http://backend2;
}
}What happens if a request is made to /app/v3/page?
Consider prefix matching rules and which location block matches the request URI.
The request URI /app/v3/page matches the prefix /app/ but not /app/v2/. NGINX routes to the location with the longest matching prefix, which is /app/.
Consider this NGINX configuration:
location /images/ {
root /data;
}
location ~* \.(gif|jpg|jpeg)$ {
root /images;
}What location block handles a request for /images/cat.jpg?
Remember that regex locations have higher priority than prefix locations if they match.
NGINX first checks prefix locations, but if a regex location matches, it takes priority. Since the request URI ends with .jpg, the regex location handles it.
An NGINX server has these location blocks:
location /api/ {
proxy_pass http://api_backend;
}
location /api/v1/ {
proxy_pass http://api_v1_backend;
}A request to /api/v1/users is proxied to http://api_v1_backend/api/v1/users instead of http://api_v1_backend/users. Why?
Check how proxy_pass handles URI rewriting with and without trailing slashes.
Without a trailing slash in proxy_pass, NGINX passes the full request URI to the upstream without stripping the location prefix. Adding a trailing slash fixes the URI rewriting for the correct backend.
You have multiple overlapping location blocks in NGINX. What is the best practice to control routing precisely?
Think about how NGINX prioritizes exact, prefix, and regex locations.
Exact matches (=) have the highest priority, followed by longest prefix matches, then regex matches. Using exact matches for specific URIs and regex for patterns helps control routing clearly.