Bird
Raised Fist0
Nginxdevops~7 mins

Nested location blocks 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 to handle different parts of a website differently. Nested location blocks in nginx let you match URLs inside other matched URLs to apply specific rules.
When you want to serve static files differently inside a specific folder of your website.
When you want to apply special headers or redirects only to a sub-path inside a main path.
When you want to proxy some requests to one backend and others inside that path to a different backend.
When you want to restrict access to a subdirectory but allow the main directory to be public.
Config File - nginx.conf
nginx.conf
server {
    listen 80;
    server_name example.com;

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

        location /images/thumbnails/ {
            root /var/www/thumbnails;
            add_header X-Thumbnail "true";
        }
    }

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

This config defines a server listening on port 80 for example.com.

The location /images/ block serves files from /var/www/static.

Inside it, the nested location /images/thumbnails/ block serves files from /var/www/thumbnails and adds a custom header.

The location / block serves the main website files.

Commands
Check the nginx configuration file for syntax errors before applying changes.
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 HEAD request to check the headers for a file inside the nested location block.
Terminal
curl -I http://example.com/images/thumbnails/pic1.jpg
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Date: Wed, 01 Jan 2025 12:00:00 GMT Content-Type: image/jpeg Content-Length: 12345 Last-Modified: Tue, 31 Dec 2024 10:00:00 GMT Connection: keep-alive X-Thumbnail: true
Send a HEAD request to check the headers for a file inside the parent location block but outside the nested one.
Terminal
curl -I http://example.com/images/photo.jpg
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Date: Wed, 01 Jan 2025 12:00:00 GMT Content-Type: image/jpeg Content-Length: 54321 Last-Modified: Tue, 31 Dec 2024 09:00:00 GMT Connection: keep-alive
Key Concept

If you remember nothing else from this pattern, remember: nested location blocks let you apply more specific rules inside broader URL matches.

Common Mistakes
Defining nested location blocks with paths that do not start with the parent location's prefix.
nginx matches nested locations only if their paths are sub-paths of the parent; otherwise, they are ignored or cause confusion.
Always start nested location paths with the parent location's path prefix exactly.
Using 'root' directive inconsistently inside nested locations causing wrong file paths.
Each 'root' resets the base directory, so nested roots must be carefully set to avoid serving wrong files.
Set 'root' carefully in nested blocks or use 'alias' if needed to avoid path conflicts.
Summary
Use nested location blocks to apply specific rules inside a broader URL path.
Test nginx config syntax with 'nginx -t' before reloading to avoid downtime.
Verify behavior by sending requests to URLs inside and outside nested locations.

Practice

(1/5)
1. What is the main purpose of using nested location blocks in an nginx configuration?
easy
A. To automatically update nginx software
B. To increase server hardware performance
C. To organize URL handling inside parent paths for clearer rules
D. To disable logging for specific URLs

Solution

  1. Step 1: Understand the role of location blocks

    Location blocks define how nginx handles requests for specific URL paths.
  2. Step 2: Recognize the benefit of nesting

    Nested location blocks allow specific rules for sub-paths without repeating the parent path, making configuration clearer.
  3. Final Answer:

    To organize URL handling inside parent paths for clearer rules -> Option C
  4. Quick Check:

    Nested location blocks = organize URL handling [OK]
Hint: Nested blocks group URL rules under parent paths [OK]
Common Mistakes:
  • Thinking nested blocks improve hardware speed
  • Confusing nested blocks with software updates
  • Assuming nested blocks disable logging
2. Which of the following is the correct syntax to define a nested location block inside location /app/ in nginx?
easy
A. location /app/ { location api/ { proxy_pass http://backend; } }
B. location /app/ { location /appapi/ { proxy_pass http://backend; } }
C. location /app/ { location /app/api/ { proxy_pass http://backend; } }
D. location /app/ { location /api/ { proxy_pass http://backend; } }

Solution

  1. Step 1: Check nested location path relative to parent

    Nested location inside location /app/ should define sub-paths relative to /app/, so api/ without leading slash is correct.
  2. Step 2: Validate syntax correctness

    location /app/ { location api/ { proxy_pass http://backend; } } uses location api/ inside location /app/, which is valid and clear.
  3. Final Answer:

    location /app/ { location api/ { proxy_pass http://backend; } } -> Option A
  4. Quick Check:

    Nested path is relative and omits leading slash [OK]
Hint: Nested location paths omit parent prefix and leading slash inside block [OK]
Common Mistakes:
  • Repeating full parent path in nested location
  • Missing leading slash in nested path
  • Combining parent and child paths incorrectly
3. Given this nginx config snippet:
location /shop/ {
  root /var/www/html;
  location /cart/ {
    proxy_pass http://cart_backend;
  }
}
What happens when a user requests /shop/cart/view?
medium
A. Request serves static file /var/www/html/shop/cart/view
B. Request is proxied to http://cart_backend/view
C. Request returns 404 Not Found
D. Request is proxied to http://cart_backend/shop/cart/view

Solution

  1. Step 1: Identify matching location block

    Request /shop/cart/view matches nested location /cart/ inside location /shop/.
  2. Step 2: Understand proxy_pass behavior

    Proxy_pass inside nested block forwards request path after /cart/, so /view is sent to http://cart_backend.
  3. Final Answer:

    Request is proxied to http://cart_backend/view -> Option B
  4. Quick Check:

    Nested proxy_pass strips matched prefix [OK]
Hint: Nested proxy_pass forwards sub-path after nested location [OK]
Common Mistakes:
  • Assuming static file serving instead of proxy
  • Including full original path in proxy_pass
  • Expecting 404 due to nested block
4. Identify the error in this nginx config snippet:
location /api/ {
  location /v1/ {
    proxy_pass http://api_v1_backend;
  }
  location /v2/ {
    proxy_pass http://api_v2_backend;
  }
}
medium
A. Nested location blocks cannot be used inside another location
B. No error; configuration is valid
C. proxy_pass URLs must include trailing slash
D. Nested location paths should not start with a slash

Solution

  1. Step 1: Recall nested location path syntax

    Nested location paths inside a parent location should be relative and not start with a slash.
  2. Step 2: Check given nested paths

    Nested locations use /v1/ and /v2/ starting with slash, which is incorrect.
  3. Final Answer:

    Nested location paths should not start with a slash -> Option D
  4. Quick Check:

    Nested paths omit leading slash [OK]
Hint: Nested location paths omit leading slash [OK]
Common Mistakes:
  • Thinking nested locations are disallowed
  • Believing proxy_pass must have trailing slash
  • Assuming config is valid as is
5. You want to serve static files from /var/www/app for /app/ URLs, but proxy API requests under /app/api/ to http://api_backend. Which nested location block setup is correct?
hard
A. location /app/ { root /var/www/app; location api/ { proxy_pass http://api_backend; } }
B. location /app/ { root /var/www/app; location /api/ { proxy_pass http://api_backend; } }
C. location /app/ { root /var/www/app; location /app/api/ { proxy_pass http://api_backend; } }
D. location /app/ { root /var/www/app; location /appapi/ { proxy_pass http://api_backend; } }

Solution

  1. Step 1: Set root for /app/ static files

    Use root /var/www/app; inside location /app/ to serve static files.
  2. Step 2: Define nested location for API proxy

    Nested location for /app/api/ should be location api/ without leading slash inside location /app/.
  3. Step 3: Verify proxy_pass target

    Proxy_pass points to http://api_backend correctly.
  4. Final Answer:

    location /app/ { root /var/www/app; location api/ { proxy_pass http://api_backend; } } -> Option A
  5. Quick Check:

    Nested path omits /, root set for static, proxy for api [OK]
Hint: Nested location paths omit leading slash; root applies to parent [OK]
Common Mistakes:
  • Repeating full path in nested location
  • Using leading slash in nested location
  • Misplacing root directive inside nested block