Skip to main content

Web servers and networking · Intermediate · 16 min

Write Nginx location blocks that match what you expect

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · Nginx 1.30.8

You will build a practice Nginx 1.30 server where every location block labels its responses, predict which block answers each of twelve URLs, check your answers with curl, and fix the alias, regex-order and proxy_pass mistakes that catch most people out.

On this page

Most Nginx surprises are not bugs in Nginx. A request lands in a different location block from the one you had in mind, and the page, header or proxy rule you wrote never runs. The selection rules are short, but they are not "first match wins" and they are not "longest match wins" either.

In this tutorial you build a practice server on port 8080 with twelve location blocks. Each block adds an X-Location header naming itself, so curl tells you exactly which block answered. You predict the result for twelve URLs before you look, then fix three classic mistakes: the alias trailing slash, a regex that grabs more than you meant, and proxy_pass keeping or stripping the path.

The paths are those of the Nginx 1.30 package from nginx.org, which reads /etc/nginx/conf.d/*.conf. Install it first with /tutorials/install-nginx-on-ubuntu-26-04. The practice server only listens on port 8080 and on 127.0.0.1:9000, so it does not touch the sites you already serve on port 80.

Step 1 · Create the practice files

Some blocks serve real files, so create a small web root with a page, a stylesheet folder, documentation, a single-page app and a download.

Bash
nginx -v
sudo mkdir -p /var/www/locations-demo/static /var/www/locations-demo/docs \
  /var/www/locations-demo/app /var/www/locations-demo/downloads
echo 'index page' | sudo tee /var/www/locations-demo/index.html
echo 'not really a png' | sudo tee /var/www/locations-demo/static/logo.png
echo 'the guide' | sudo tee /var/www/locations-demo/docs/guide.txt
echo '<div id="root">single-page app shell</div>' | sudo tee /var/www/locations-demo/app/index.html
echo 'quarterly report' | sudo tee /var/www/locations-demo/downloads/report.txt

Next, write a helper script. For each path you give it, it prints the path, the status code and the X-Location header, or none when the header is missing.

Bash
mkdir -p ~/nginx-locations-demo
cat > ~/nginx-locations-demo/which.sh <<'SH'
#!/usr/bin/env bash
# Print the status code and X-Location header for each path on the practice server.
for path in "$@"; do
  headers=$(curl -s -o /dev/null -D - "http://127.0.0.1:8080${path}" | tr -d '\r')
  status=$(printf '%s\n' "$headers" | awk 'NR == 1 {print $2}')
  where=$(printf '%s\n' "$headers" | awk -F': ' 'tolower($1) == "x-location" {print $2}')
  printf '%-24s %s %s\n' "$path" "${status:-none}" "${where:-none}"
done
SH
chmod +x ~/nginx-locations-demo/which.sh

Check it worked

Bash
cat /var/www/locations-demo/docs/guide.txt /var/www/locations-demo/downloads/report.txt
ls -l ~/nginx-locations-demo/which.sh

You see the guide and quarterly report, and the script shows x permission bits. nginx -v printed nginx version: nginx/1.30.8 or a later 1.30 patch.

Step 2 · Write the practice server

Two parts of the configuration change later in the tutorial, so they live in small files of their own that the main block pulls in with include. An include is pasted in place, which matters for regex blocks, as you will see. Create those two files first.

Bash
sudo mkdir -p /etc/nginx/locations-demo
sudo tee /etc/nginx/locations-demo/files.conf > /dev/null <<'CONF'
location /files/ {
    add_header X-Location "files-alias" always;
    alias /var/www/locations-demo/downloads;
}
CONF
sudo tee /etc/nginx/locations-demo/admin.conf > /dev/null <<'CONF'
location ~ ^/admin/ {
    add_header X-Location "admin-regex" always;
    return 200 "admin area\n";
}
CONF

The /files/ block has a deliberate mistake in it. Leave it for now.

Now the main file. It holds the practice server on port 8080 and a tiny backend on 127.0.0.1:9000 that replies with the exact URI it received, so you can see what proxy_pass sends.

Bash
sudo tee /etc/nginx/conf.d/locations-demo.conf > /dev/null <<'CONF'
server {
    listen 8080;
    server_name locations.test;
    root /var/www/locations-demo;

    location = / {
        add_header X-Location "exact-root" always;
        return 200 "home\n";
    }

    location / {
        add_header X-Location "catch-all" always;
        try_files $uri $uri/ =404;
    }

    location ^~ /static/ {
        add_header X-Location "static-no-regex" always;
    }

    location ~* \.(png|jpe?g|gif|webp)$ {
        add_header X-Location "images-regex" always;
        return 200 "image\n";
    }

    location ~ \.php$ {
        add_header X-Location "php-regex" always;
        return 200 "php\n";
    }

    include /etc/nginx/locations-demo/admin.conf;

    location /docs/ {
        add_header X-Location "docs-root" always;
    }

    location /manual/ {
        add_header X-Location "manual-alias" always;
        alias /var/www/locations-demo/docs/;
    }

    include /etc/nginx/locations-demo/files.conf;

    location /app/ {
        add_header X-Location "spa" always;
        try_files $uri $uri/ /app/index.html;
    }

    location /api/ {
        add_header X-Location "api-proxy" always;
        proxy_pass http://127.0.0.1:9000;
    }

    location /legacy/ {
        add_header X-Location "legacy-proxy" always;
        proxy_pass http://127.0.0.1:9000/;
    }
}

server {
    listen 127.0.0.1:9000;

    location / {
        return 200 "backend saw $request_uri\n";
    }
}
CONF

The modifier before each path decides how it is compared:

  • = / is an exact match. It handles / and nothing else.
  • /, /docs/, /app/ and the other plain paths are prefix matches. /docs/ matches any URI that starts with those six characters.
  • ^~ /static/ is a prefix match that, when it is the longest prefix, stops Nginx from trying any regex.
  • ~ is a case-sensitive regular expression and ~* a case-insensitive one.

always on add_header sends the header on error responses such as 404 too, which you need to see where a missing file was looked up. One warning for your own sites: a block that has any add_header line drops every add_header inherited from the server level, so repeat security headers inside such blocks.

Test the files, then reload:

Bash
sudo nginx -t
Bash
sudo systemctl reload nginx

Check it worked

Bash
curl -s -i http://127.0.0.1:8080/

The response is HTTP/1.1 200 OK with X-Location: exact-root among the headers and home as the body. If nginx -t complained instead, it names the file and line.

Step 3 · Predict, then test, twelve URLs

Before you run anything, write down which block you think answers each URL, and whether you expect a 200 or a 404. Use the configuration above and your current instincts.

  1. /
  2. /index.html
  3. /static/logo.png
  4. /images/logo.png
  5. /docs/diagram.PNG
  6. /admin/login.php
  7. /admin/users
  8. /docs/guide.txt
  9. /manual/guide.txt
  10. /files/report.txt
  11. /app/settings/profile
  12. /api/users?page=2

Now check:

Bash
cd ~/nginx-locations-demo
./which.sh / /index.html /static/logo.png /images/logo.png /docs/diagram.PNG \
  /admin/login.php /admin/users /docs/guide.txt /manual/guide.txt \
  /files/report.txt /app/settings/profile '/api/users?page=2'

The ? URL is in quotes so your shell does not treat it as a wildcard. The output is:

Text
/                        200 exact-root
/index.html              200 catch-all
/static/logo.png         200 static-no-regex
/images/logo.png         200 images-regex
/docs/diagram.PNG        200 images-regex
/admin/login.php         200 php-regex
/admin/users             200 admin-regex
/docs/guide.txt          200 docs-root
/manual/guide.txt        200 manual-alias
/files/report.txt        404 files-alias
/app/settings/profile    200 spa
/api/users?page=2        200 api-proxy

Check it worked

Count your correct predictions. Most people get the first two and the last one right, and miss at least one of 4, 5, 6 and 10. The next step explains each of them.

Step 4 · Work through the matching order

Nginx does not read location blocks top to bottom and stop at the first that fits. For each request it follows this order, against the URI without its query string:

  1. Exact blocks. If an = block equals the URI, it wins straight away. That is why / went to exact-root while /index.html did not: an exact block never matches anything longer.
  2. Longest prefix. Nginx finds the longest plain prefix that matches and remembers it. For /docs/diagram.PNG that is /docs/; for /images/logo.png it is /.
  3. ^~ stops here. If that longest prefix has ^~, it wins and no regex is tried. So /static/logo.png stayed in static-no-regex even though it ends in .png.
  4. Regexes in file order. Otherwise Nginx tries each regex block in the order it appears in the file, includes pasted in place, and the first that matches wins. Its position in the file is all that counts, not how specific it looks. /docs/diagram.PNG went to images-regex because ~* ignores case, and /admin/login.php went to php-regex because that block comes before the admin regex.
  5. Fallback. If no regex matches, the remembered longest prefix handles the request: /docs/guide.txt went to docs-root, /api/users to api-proxy.

A plain prefix is a string comparison, nothing more. /static/ does not match /staticfile.png, and a prefix written without a trailing slash, such as /static, would.

Check it worked

Predict these two, then run them:

Bash
~/nginx-locations-demo/which.sh /static/app.php /staticfile.png

/static/app.php gives 404 static-no-regex: the ^~ prefix wins before the PHP regex is tried, and there is no such file. /staticfile.png gives 200 images-regex, because /static/ is not a prefix of it.

Step 5 · Fix the alias trailing-slash trap

root and alias both turn a URI into a file path, in different ways:

  • root appends the whole URI. In /docs/, /docs/guide.txt becomes /var/www/locations-demo + /docs/guide.txt.
  • alias replaces the part of the URI that matched the location. In /manual/, the /manual/ part of /manual/guide.txt is swapped for /var/www/locations-demo/docs/, giving the same file.

Because alias is a plain text swap, the slashes on both sides must agree. The /files/ block ends in a slash but its alias does not, so /files/report.txt became downloads + report.txt. The error log shows the path Nginx tried:

Bash
sudo grep -F 'downloadsreport.txt' /var/log/nginx/error.log

The line ends with something like open() "/var/www/locations-demo/downloadsreport.txt" failed (2: No such file or directory). Rewrite the block with a trailing slash on the alias:

Bash
sudo tee /etc/nginx/locations-demo/files.conf > /dev/null <<'CONF'
location /files/ {
    add_header X-Location "files-alias" always;
    alias /var/www/locations-demo/downloads/;
}
CONF
sudo nginx -t
Bash
sudo systemctl reload nginx

The opposite mistake is worse. A location without a slash, such as location /files, with an alias that has one lets a request for /files../ step one folder above the alias directory. Keep the slashes matched on both sides, or use root when the folder name equals the URI prefix.

Check it worked

Bash
~/nginx-locations-demo/which.sh /files/report.txt
curl -s http://127.0.0.1:8080/files/report.txt

The first line is now /files/report.txt 200 files-alias, and the body is quarterly report.

Step 6 · Serve a single-page app with try_files

A single-page app handles its own routes in the browser, so /app/settings/profile has no file on disk. try_files $uri $uri/ /app/index.html checks, in order, for a file, then a folder, then falls back to the app shell. The last item is an internal redirect: Nginx runs location matching again for /app/index.html, which lands in the same /app/ block.

PHP front controllers use the same idea with a different last item: try_files $uri $uri/ /index.php?$query_string; hands every unknown path to index.php, which a location ~ \.php$ block passes on to PHP-FPM.

The fallback has a cost. A missing script or stylesheet also gets the shell, with status 200, so the browser reports a confusing parse error instead of a clear 404. It also wastes bytes: on a prepaid mobile plan, as many readers across Africa use, each wrong reply is data the visitor paid for. Keep built assets under a folder like /static/ with =404 behaviour, and only route page URLs through the fallback.

Check it worked

Bash
curl -s http://127.0.0.1:8080/app/settings/profile
~/nginx-locations-demo/which.sh /app/missing.js

The body is <div id="root">single-page app shell</div>, and the missing script shows 200 spa, which is the trap described above.

Step 7 · Scope a regex with a nested location

/admin/login.php went to the general PHP block because it comes first in the file. Moving regex blocks around works until someone adds another one. A sturdier fix is to make /admin/ a prefix block and put the regex inside it. Nginx checks regexes nested in the matched prefix before the top-level ones, so the inner one wins for admin URLs and has no effect anywhere else.

Replace the admin file:

Bash
sudo tee /etc/nginx/locations-demo/admin.conf > /dev/null <<'CONF'
location /admin/ {
    add_header X-Location "admin-prefix" always;
    return 200 "admin area\n";

    location ~ \.php$ {
        add_header X-Location "admin-php" always;
        return 200 "admin php\n";
    }
}
CONF
sudo nginx -t
Bash
sudo systemctl reload nginx

A nested block does not inherit add_header or return from its parent once it sets its own, so give it everything it needs.

Check it worked

Bash
~/nginx-locations-demo/which.sh /admin/login.php /admin/users /blog/post.php

You see 200 admin-php, 200 admin-prefix and 200 php-regex. The general PHP block still handles PHP outside /admin/.

Step 8 · Choose whether proxy_pass strips the path

The two proxy blocks differ by one character, a / at the end of the proxy_pass address:

  • proxy_pass http://127.0.0.1:9000; has no URI, so Nginx forwards the request URI unchanged.
  • proxy_pass http://127.0.0.1:9000/; has a URI (/), so Nginx replaces the part that matched the location with it. /legacy/users reaches the backend as /users.
Bash
curl -s 'http://127.0.0.1:8080/api/users?page=2'
curl -s 'http://127.0.0.1:8080/legacy/users?page=2'

The first prints backend saw /api/users?page=2 and the second backend saw /users?page=2. The query string survives either way.

Use the stripping form when an app expects to live at / but you publish it under a sub-path. Two related rules:

  • Keep the slashes matched here too. location /legacy with proxy_pass http://127.0.0.1:9000/; turns /legacy/users into something like //users.
  • A regex location cannot have a URI on proxy_pass; nginx -t rejects it. Rewrite the path with rewrite in that case.

Because /api/ ends in a slash and proxies, a request for /api without one gets a 301 redirect to /api/.

Check it worked

Bash
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://127.0.0.1:8080/api

It prints 301 followed by a URL ending in /api/.

Step 9 · Remove the practice server

The practice files are not part of any real site. The commands below delete only what this tutorial created: one file in conf.d, the locations-demo folder of includes, the web root and the helper script. Check the names before you run them.

Bash
sudo rm -f /etc/nginx/conf.d/locations-demo.conf
sudo rm -rf /etc/nginx/locations-demo /var/www/locations-demo
rm -rf ~/nginx-locations-demo
sudo nginx -t
Bash
sudo systemctl reload nginx

Check it worked

Bash
curl -sS http://127.0.0.1:8080/

curl reports Failed to connect because nothing listens on port 8080 any more. Your other sites are unchanged.

When you next write location blocks for a real site, add a temporary X-Location header to each one and repeat this check against the URLs that matter before you remove it.

Next steps

  • Give each of your sites its own server block: /tutorials/host-multiple-sites-with-nginx-server-blocks.
  • Put a real application behind proxy_pass: /tutorials/nginx-reverse-proxy-for-a-node-app.
  • Send all traffic to one HTTPS address: /tutorials/redirect-http-to-https-and-www-in-nginx.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.