Beginner Fundamentals

Location Blocks and Matching

The location block decides how Nginx handles a request based on its URI. It is one of the most powerful and most misunderstood parts of the config.

Prefix Match

The default form matches the start of the URI:

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

This matches /images/logo.png, /images/icons/a.png, and so on.

Exact Match

The = modifier matches the URI exactly, nothing more:

location = /favicon.ico {
    root /var/www/example;
}

This only matches /favicon.ico. Exact matches are fast and checked first.

Regex Match

Use ~ for case-sensitive regex and ~* for case-insensitive:

location ~* \.(jpg|png|gif)$ {
    expires 30d;
}

This matches any URI ending in .jpg, .png, or .gif regardless of case.

Match Priority

Nginx does not simply read top to bottom. It chooses in this order:

  1. Exact = match
  2. Longest prefix match marked with ^~
  3. First matching regex (~ or ~*)
  4. Longest plain prefix match

A Common Combination

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

location ~* \.(css|js)$ {
    expires 7d;
}

The first handles general pages; the second adds caching for assets.