Bird
Raised Fist0
Nginxdevops~5 mins

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
When a web server receives a request, it needs to decide how to handle it. Location blocks in nginx help the server match parts of the web address to specific rules or files to serve. This makes it easy to organize and control how different URLs are handled.
When you want to serve different content for different parts of your website, like images in one folder and web pages in another.
When you need to redirect certain URLs to other locations or servers.
When you want to apply special rules like caching or access control to specific URL paths.
When you want to serve a single-page application and need to route all requests to one file.
When you want to block access to certain URLs or file types.
Config File - nginx.conf
nginx.conf
server {
    listen 80;
    server_name example.com;

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

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

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

    location = /favicon.ico {
        access_log off;
        log_not_found off;
    }
}

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

The location / block serves files from /var/www/html for the main website.

The location /images/ block serves image files from /var/www/assets.

The location /api/ block forwards requests to a backend server running on localhost port 3000.

The location = /favicon.ico block matches exactly the favicon request and disables logging for it.

Commands
This command tests the nginx configuration file for syntax errors before applying it. It helps catch mistakes early.
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
This command reloads nginx to apply the new configuration without stopping the server. It ensures changes take effect smoothly.
Terminal
sudo systemctl reload nginx
Expected OutputExpected
No output (command runs silently)
This command checks the HTTP headers for a request to the images location to verify it is served correctly.
Terminal
curl -I http://example.com/images/logo.png
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Content-Type: image/png Content-Length: 5234 Connection: keep-alive
-I - Fetch only HTTP headers without the body
This command tests that requests to the /api/ location are properly forwarded to the backend server.
Terminal
curl -I http://example.com/api/users
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Content-Type: application/json Connection: keep-alive
-I - Fetch only HTTP headers without the body
Key Concept

If you remember nothing else from this pattern, remember: location blocks let nginx match URL paths to specific actions or files to control how requests are handled.

Common Mistakes
Using 'root' inside a location block without the trailing slash on the location path.
This can cause nginx to look for files in unexpected directories because 'root' appends the full request URI after the location prefix.
Use 'alias' instead of 'root' when the location path does not match the filesystem path structure, or ensure the location path ends with a slash if using 'root'.
Forgetting to reload nginx after changing the configuration.
Changes won't take effect until nginx reloads the config, so the server keeps using the old rules.
Always run 'sudo nginx -t' to test, then 'sudo systemctl reload nginx' to apply changes.
Using '=' prefix in location block for a path but expecting it to match sub-paths.
The '=' prefix matches the exact request URI only, so sub-paths won't match and may cause 404 errors.
Use prefix matching (no '=') for paths that include subdirectories, or use regex if needed.
Summary
Use location blocks in nginx.conf to match URL paths and define how requests are handled.
Test your configuration with 'nginx -t' before reloading to avoid errors.
Reload nginx after changes to apply new rules without downtime.
Use 'curl' commands to verify that different locations serve or proxy content correctly.

Practice

(1/5)
1. What is the main purpose of a location block in an nginx configuration?
easy
A. To specify the server's hostname
B. To set the server's IP address
C. To define how nginx handles requests for specific URL paths
D. To configure the database connection

Solution

  1. Step 1: Understand the role of location blocks

    Location blocks in nginx specify rules for handling requests based on URL paths.
  2. Step 2: Compare options with location block purpose

    Only To define how nginx handles requests for specific URL paths correctly describes this purpose; others relate to different server settings.
  3. Final Answer:

    To define how nginx handles requests for specific URL paths -> Option C
  4. Quick Check:

    Location blocks control URL handling = D [OK]
Hint: Location blocks match URLs to control request handling [OK]
Common Mistakes:
  • Confusing location blocks with server settings
  • Thinking location blocks set server IP or hostname
  • Mixing location blocks with database configs
2. Which of the following is the correct syntax to define a location block that matches the exact URL /about?
easy
A. location /about { }
B. location ~ /about { }
C. location ^~ /about { }
D. location = /about { }

Solution

  1. Step 1: Understand location modifiers

    The = modifier matches the exact URL path.
  2. Step 2: Match syntax to exact URL

    location = /about { } uses = /about which matches exactly '/about'. Others match prefixes or regex.
  3. Final Answer:

    location = /about { } -> Option D
  4. Quick Check:

    Exact match uses '=' modifier = C [OK]
Hint: Use '=' for exact URL match in location block [OK]
Common Mistakes:
  • Using no modifier for exact match
  • Confusing regex (~) with exact match
  • Using ^~ which is prefix, not exact
3. Given this nginx config snippet:
location /images/ {
  root /data;
}

What is the full file path nginx will serve for a request to /images/pic.jpg?
medium
A. /data/pic.jpg
B. /data/images/pic.jpg
C. /images/pic.jpg
D. /data/images/

Solution

  1. Step 1: Understand root directive with location

    The root directive appends the part of the URI after the location prefix to the root path.
  2. Step 2: Combine root and URI

    Location prefix is /images/, request URI is /images/pic.jpg, so the part after prefix is pic.jpg. Root is /data, so full path is /data/pic.jpg.
  3. Final Answer:

    /data/pic.jpg -> Option A
  4. Quick Check:

    root + URI after location prefix = /data/pic.jpg [OK]
Hint: root + URI after location prefix = file path served [OK]
Common Mistakes:
  • Assuming root combines with full URI
  • Using full URI instead of URI after location prefix
  • Confusing alias with root behavior
4. Identify the error in this nginx location block:
location /static/ {
  alias /var/www/static;
}
medium
A. Missing trailing slash in alias path
B. alias should be root here
C. location path should not end with slash
D. No error, configuration is correct

Solution

  1. Step 1: Understand alias usage

    When using alias with a location ending with a slash, the alias path must also end with a slash.
  2. Step 2: Check alias path

    Alias path /var/www/static lacks trailing slash, causing incorrect file path resolution.
  3. Final Answer:

    Missing trailing slash in alias path -> Option A
  4. Quick Check:

    Alias path must end with '/' if location ends with '/' = B [OK]
Hint: Alias path needs trailing slash if location ends with slash [OK]
Common Mistakes:
  • Using root instead of alias incorrectly
  • Omitting trailing slash on alias path
  • Thinking location path cannot end with slash
5. You want nginx to serve static files from /var/www/app/static when users request URLs starting with /static/, but you want to avoid duplicating the /static/ part in the file path. Which location block correctly achieves this?
hard
A. location /static/ { root /var/www/app/static; }
B. location /static/ { alias /var/www/app/static/; }
C. location /static/ { alias /var/www/app/static; }
D. location /static/ { root /var/www/app; }

Solution

  1. Step 1: Understand alias vs root behavior

    Alias replaces the location prefix with the alias path exactly, avoiding duplication.
  2. Step 2: Check trailing slashes for alias

    Alias path must end with a slash to match location ending with slash, ensuring correct path mapping.
  3. Step 3: Evaluate options

    location /static/ { alias /var/www/app/static/; } uses alias with trailing slash, correctly mapping /static/file to /var/www/app/static/file. Others either duplicate path or miss slash.
  4. Final Answer:

    location /static/ { alias /var/www/app/static/; } -> Option B
  5. Quick Check:

    Alias with trailing slash avoids duplication = A [OK]
Hint: Use alias with trailing slash to avoid path duplication [OK]
Common Mistakes:
  • Using root causing duplicated /static/ in path
  • Omitting trailing slash on alias path
  • Confusing alias and root usage