NGINX Location Matcher & Regex Priority Tester

Test and debug NGINX location block matching precedence rules (= exact, ^~ preferential prefix, ~ / ~* regex, and standard prefix) with step-by-step evaluation traces.

One URI per line or single path

How NGINX Location Matching Precedence Works

1

1. Exact Match (=)

Checks for exact URI equality. If matched, NGINX stops searching immediately and serves the request.

2

2. Preferential Prefix (^~)

Finds the longest matching prefix. If the longest prefix has ^~, regular expression checks are skipped entirely.

3

3. Regular Expressions (~ / ~*)

Evaluates regexes in the exact top-to-bottom order of your file. The first matching regex wins.

Tool Options

Regex Order Dependency

Unlike prefix rules which pick the longest match, regular expressions match in file order. Placing a broad regex too early can hijack specific API routes.

Prefix vs Regex Conflicts

Standard prefix blocks (e.g. location /api/) are overridden by regexes (e.g. location ~* \.json$) unless guarded by ^~.

Multi-URI Batch Testing

Test dozens of endpoints at once against your proxy configuration to verify routing before reloading NGINX in production.

Your Data Privacy

Web Tool
Privacy-First Architecture
Most of our web tools process your data entirely in-browser. Where server processing is technically required, payloads are evaluated statelessly in-memory and are never stored, saved, or logged.
REST API
Stateless In-Memory Processing
When you use our API endpoints, your requests are processed strictly in-memory without persistent database storage, disk logging, or data retention.
Want to learn more about how we safeguard your information and infrastructure?
Read our full Privacy Policy for detailed security standards, data retention principles, and compliance guarantees.

What does the NGINX Location Matcher & Regex Priority Tester do?

The NGINX Location Matcher & Regex Priority Tester parses NGINX configuration blocks and evaluates request URIs against the official NGINX location matching precedence algorithm (= exact match, ^~ preferential prefix, ~ / ~* regular expressions, and standard prefix matches). It generates step-by-step evaluation traces to diagnose routing conflicts and unexpected regex overrides.

Core Concepts

Understanding NGINX location matching precedence:

  1. Exact Match (=): Checks for identical URI equality. If matched, NGINX terminates searching immediately.
  2. Preferential Prefix (^~): Locates the longest matching prefix. If this prefix contains ^~, regular expression checks are completely skipped.
  3. Regular Expressions (~ & ~*): Evaluated in top-to-bottom file order (case-sensitive ~ and case-insensitive ~*). The first matching regex wins.
  4. Standard Prefix: If no regex matches, the longest standard prefix without ^~ is chosen.

How to use the tool?

  1. Enter NGINX Config: Paste your NGINX location blocks into the configuration editor or click Load Sample Rules.
  2. Specify Test URIs: Enter one or more request paths (one per line) into the URI input box.
  3. Test & Inspect: Click Test Location Matching to review the matched rule summary table and click Copy to copy the precedence breakdown.

Related Developer Utilities

If you work with NGINX, web servers, and reverse proxies, explore these complementary tools:

REST API Integration

Blueutils provides a free REST API endpoint (POST https://blueutils.com/api/nginx/nginx-location-matcher) to programmatically emulate and test NGINX location block matching logic and precedence hierarchies against request URIs.

API Request Parameters

Name Type Description Example
rawText String NGINX configuration containing location blocks. "location /api/ {\n proxy_pass http://backend;\n}"
testUris Array Array of request URI paths to test. Default: ["/"]. ["/api/v1/users", "/images/logo.png"]

API Request Payload Examples

cURL

curl -X POST https://blueutils.com/api/nginx/nginx-location-matcher \
  -H "Content-Type: application/json" \
  -d '{
    "rawText": "location = / { }\nlocation ^~ /images/ { }\nlocation ~* \\.(png|jpg)$ { }\nlocation /api/ { }\nlocation / { }",
    "testUris": ["/", "/images/logo.png", "/api/v1/users", "/about"]
  }'

Python

import requests

url = "https://blueutils.com/api/nginx/nginx-location-matcher"
payload = {
    "rawText": "location = / { }\nlocation ^~ /images/ { }\nlocation ~* \\.(png|jpg)$ { }\nlocation /api/ { }\nlocation / { }",
    "testUris": ["/", "/images/logo.png", "/api/v1/users", "/about"]
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonPayload = """
            {
                "rawText": "location = / { }\\nlocation /api/ { }",
                "testUris": ["/api/v1/users"]
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://blueutils.com/api/nginx/nginx-location-matcher"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

API Response Parameters

Name Type Description Example
isValid Boolean Indicates whether configuration parsed successfully. true
locationsCount Number Total count of parsed location blocks. 5
results Array Array of test results for each evaluated URI. [{ "uri": "/", "matched": true, ... }]

API Response Payload Examples

Success Response (HTTP 200 OK)

{
  "isValid": true,
  "locationsCount": 5,
  "results": [
    {
      "uri": "/images/logo.png",
      "matched": true,
      "matchedLocation": {
        "id": 2,
        "lineNumber": 4,
        "modifier": "^~",
        "pattern": "/images/",
        "type": "preferential-prefix",
        "rawHeader": "location ^~ /images/"
      },
      "matchType": "Preferential Prefix (^~)",
      "reason": "Longest matching prefix \"/images/\" has \"^~\" modifier at line 4. Regular expressions search skipped.",
      "evaluationSteps": []
    }
  ]
}

Validation Failure Response (HTTP 400 Bad Request)

{
  "isValid": false,
  "error": "No valid \"location\" blocks detected. Expected syntax: location [=|~|~*|^~] <pattern> { ... }"
}

Rate Limit Exceeded Response (HTTP 429 Too Many Requests)

{
  "error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}

Why use an API to test NGINX location matching?

Integrating the NGINX Location Matcher API into CI/CD configuration linters, deployment pipelines, or AI agent tool calling provides key benefits:

  • Rapid Script Validation: Verifies complex multi-location proxy routing before reloading production web servers.
  • Optimized Token Efficiency for AI Agents: LLMs frequently miscalculate NGINX prefix vs regex priority rules. Calling the API evaluates precedence deterministically without token consumption.
  • Deterministic Accuracy Without Hallucinations: Ensures 100% faithful emulation of official NGINX C source code matching algorithms.

Native Usage

How to test NGINX configuration syntax and location matching locally:

Linux / Unix (Bash)

# Test NGINX configuration syntax
sudo nginx -t

# Test with temporary debug header
# Add 'add_header X-Matched-Location "api" always;' inside your location block
curl -I https://example.com/api/v1/users | grep -i X-Matched-Location

Windows (CMD / PowerShell)

:: Test NGINX configuration syntax in Windows
nginx.exe -t -c C:\nginx\conf\nginx.conf

Python

Using Python:

import re

locations = [("=", "/"), ("^~", "/images/"), ("~*", r"\.(png|jpg)$"), ("", "/api/"), ("", "/")]
uri = "/images/logo.png"

# Test exact match
exact = next((l for l in locations if l[0] == "=" and l[1] == uri), None)
print("Matched:", exact or "Checking prefix/regex...")

Java

Using Java:

public class NginxMatcherExample {
    public static void main(String[] args) {
        String uri = "/api/v1/users";
        if (uri.startsWith("/api/")) {
            System.out.println("Matched standard prefix: /api/");
        }
    }
}

Frequently Asked Questions (FAQ)

How does NGINX determine which location block matches a request?

NGINX checks exact matches (=) first. Next, it finds the longest prefix match. If that prefix has ^~, regex search is skipped. Otherwise, regular expressions (~ and ~*) are evaluated in file order. If no regex matches, the longest standard prefix is used.

Why did my regex location block override my prefix location block?

Standard prefix locations (e.g. location /api/) are overridden by matching regex blocks (e.g. location ~* \.json$) unless you add the ^~ modifier to the prefix block.

Can I test multiple URIs simultaneously?

Yes. You can paste multiple test URIs (one per line) to view an interactive summary table of matched blocks and evaluation reasons for all endpoints.

Rate Limits

UI Limits
100 uses per 15 minutes
Max payload size: 5 MB
API Limits
5 requests per 60 minutes
Max payload size: 256 KB
Need higher API rate limits, increased payload sizes, or custom developer solutions?
Contact our engineering team at support@blueutils.com for custom rate limit increases, higher quota allocations, or tailored enterprise integrations.