keepcalculator

06 Numbers and Powers

Nginx Location Directive Explained With Examples

Card No. 06·61332 · Updated · Standard formula, shown below

The Nginx location directive selects how a request URI is handled, such as serving a file, proxying to an application, or returning an error. Its behavior depends on the match type and Nginx’s selection order, so choosing the right modifier and understanding precedence are essential.

What a location block does

A location block appears inside a server block and matches the URI path of an incoming request. It can set directives for that request, including root, alias, proxy_pass, access rules, and response behavior.

For example, a server might serve ordinary pages from a document directory, send requests under /api/ to an application server, and deny access to hidden files. These rules live in separate location blocks:

server {
    listen 80;
    server_name example.test;

    root /var/www/site;

    location / {
        try_files $uri $uri/ =404;
    }

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

    location ~ /\. {
        deny all;
    }
}

The URI is the path portion of the request, such as /api/items; query arguments such as ?page=2 are not part of the location match. Nginx uses normalized URI paths for matching, including processing percent-encoded characters and resolving dot segments. This is distinct from matching the raw request line.

Location syntax and match types

The general syntax is location [modifier] URI { ... }. The modifier changes how Nginx compares the URI against the request path:

  • location = /health { ... } is an exact match. It matches only the URI /health.
  • location /images/ { ... } is a prefix match. It matches paths beginning with /images/, including /images/logo.svg.
  • location ^~ /assets/ { ... } is a prefix match that prevents a later regular-expression location from taking precedence over this prefix.
  • location ~ \.php$ { ... } uses a case-sensitive regular expression.
  • location ~* \.jpg$ { ... } uses a case-insensitive regular expression.

A location without a modifier is not a regular expression. It is a prefix match. Likewise, a regular-expression pattern is written after ~ or ~*; writing a pattern without a modifier does not make Nginx interpret it as a regex.

How Nginx chooses a location

Location selection is not simply “the first block that matches.” Nginx first checks for an exact match. If none exists, it finds the longest matching prefix. It then checks regular-expression locations in configuration order, except when the selected longest prefix uses ^~. The first matching regex wins; if none matches, Nginx uses the longest prefix.

In practical terms, an exact match is the most specific choice, while a longer prefix beats a shorter prefix. A regex can override the longest prefix unless that prefix uses ^~. This example makes the distinction clear:

location /images/ {
    # General handling for image paths
}

location ~* \.(gif|jpg|png)$ {
    # Can match image files, including those under /images/
}

A request for /images/photo.jpg matches the prefix and the regex. Since the prefix does not use ^~, Nginx checks regex locations and uses the first matching one. Changing the first block to location ^~ /images/ makes that prefix win without checking regex locations for this request.

Location processing can also involve internal redirects. Directives such as try_files can cause Nginx to look for a different URI and select a location again. Therefore, a request’s final handling may not be determined solely by the first match.

Choosing a pattern for common tasks

Choose the simplest match type that expresses the intended routing rule. Exact and prefix locations are usually easier to understand and maintain than regex rules.

  • One special endpoint: use an exact match, for example location = /health.
  • A whole URL section: use a prefix such as location /api/ or location /downloads/.
  • A file extension or pattern: use a regex, such as location ~* \.(css|js)$, when matching by suffix is genuinely useful.
  • Keep a prefix ahead of regex rules: use ^~ when requests under that prefix should not be captured by regex locations.

For example, this configuration serves static files when they exist and otherwise returns a 404:

location / {
    try_files $uri $uri/ =404;
}

This API prefix forwards requests to a local upstream:

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

Be aware that the URI portion of proxy_pass affects how the request path is forwarded. With no URI after the upstream address, as above, Nginx generally passes the request URI through. Adding a trailing path to proxy_pass can change the replacement behavior for a prefix location. Check the official directive documentation before relying on subtle path rewriting.

Common problems and misconceptions

A frequent mistake is assuming configuration order controls all location matches. Order matters among regex locations, but exact matches and longest-prefix selection follow their own rules. Another is expecting location /api to match only a directory: it also matches paths such as /apix. Use /api/ when the slash-delimited section is intended, and consider an exact block for /api if that path needs separate handling.

Regex syntax also causes confusion. In a quoted JSON or shell context, backslashes may need additional escaping, but in an Nginx configuration file a pattern such as \.php$ is commonly used to match a literal dot followed by php at the end of the URI. Regex locations are evaluated in order, so place narrower or more important patterns before broad ones.

Finally, root and alias are not interchangeable. With root, Nginx appends the request URI to the configured root path. With alias, the matched location prefix is replaced by the alias path. A mismatched trailing slash or an unexpected URI mapping can lead to missing files or incorrect paths. Test the resulting filesystem mapping rather than assuming the two directives behave alike.

Testing and troubleshooting locations

After editing configuration, validate it before reloading Nginx:

nginx -t

The command checks configuration syntax and reports errors it can detect; it does not prove that every request will route as intended. Reload the service using the method appropriate to the system, then test representative URLs with a browser or a command-line HTTP client. Check both the response status and the relevant access or error logs.

  • Test the exact path, a child path, and a similar-looking path (for example, /api, /api/items, and /apix).
  • For regex locations, test matching and non-matching file names and remember whether the expression is case-sensitive.
  • If a file is missing, verify the selected location, the root or alias mapping, filesystem permissions, and any try_files behavior.
  • If proxying behaves unexpectedly, inspect the proxy_pass URI and whether the application expects a rewritten path.

Frequently Asked Questions

Does Nginx use the first matching location?
No. It checks exact matches first, then selects the longest prefix and evaluates regex locations in order, with ^~ able to stop regex evaluation for the selected prefix.

What is the difference between location / and location = /?
location / is a prefix that can match nearly every URI path. location = / matches only the root path, exactly.

When should I use ^~?
Use it when a matching prefix should take priority over regular-expression locations. It does not make the prefix exact; it still matches paths that begin with that prefix.

Do query parameters affect location matching?
No. Nginx location matching uses the URI path, not query arguments. Requests to /search?q=one and /search?q=two have the same path for location selection.

Can two locations match the same request?
Yes. A request can match both a prefix and a regex. Nginx applies its selection rules to choose which block handles it; it does not combine the contents of every matching block.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →