Mastering Nginx location: Syntax, Matching Types, and Priority Rules

This guide explains how Nginx processes request URIs using the location directive, detailing its syntax, the four matching types, and the rule‑based priority system that determines which location block handles a request.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Mastering Nginx location: Syntax, Matching Types, and Priority Rules

Location Syntax

The location directive in Nginx defines how incoming request strings are processed for routing, caching, response control, and proxy forwarding.

Syntax:

location [=|~|~*|^~] uri { ... }

Matching Types

The optional bracketed part specifies the match type:

= – Exact match; the request string must be identical to the URI.

~ – Case‑sensitive regular expression match.

~* – Case‑insensitive regular expression match.

^~ – Not a regex; matches when the URI starts with the given literal string.

none – Same as ^~ but with a different evaluation order.

Match Categories

Ordinary match (no brackets or using ^~).

Exact match ( =).

Regex match ( ~ or ~*).

Examples

location = / {

# Exact match for the root path; no characters may follow the host name. location / { # Ordinary match; matches all requests because every URI starts with /. location ~* \.(gif|jpg|jpeg)$ { # Regex match; applies to URIs ending with .gif, .jpg, or .jpeg, case‑insensitively.

Priority of Multiple location Blocks

Search for an exact match ( =); if found, stop and use it.

Check ordinary matches for any that start with ^~; if found, stop and use the first such match, otherwise remember the best ordinary match.

Evaluate regex matches in order; if a match is found, stop and use it; otherwise fall back to the best ordinary match remembered earlier.

Nginx location priority diagram
Nginx location priority diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendConfigurationWeb serverregexlocation
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.