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:
- Exact Match (
=): Checks for identical URI equality. If matched, NGINX terminates searching immediately. - Preferential Prefix (
^~): Locates the longest matching prefix. If this prefix contains^~, regular expression checks are completely skipped. - Regular Expressions (
~&~*): Evaluated in top-to-bottom file order (case-sensitive~and case-insensitive~*). The first matching regex wins. - Standard Prefix: If no regex matches, the longest standard prefix without
^~is chosen.
How to use the tool?
- Enter NGINX Config: Paste your NGINX location blocks into the configuration editor or click Load Sample Rules.
- Specify Test URIs: Enter one or more request paths (one per line) into the URI input box.
- 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:
- NGINX to Caddyfile Converter: Convert NGINX server blocks to Caddy v2 configuration.
- Linux Logrotate Config Generator: Build log rotation policies for
/var/log/nginx/. - Crontab to Systemd Timer Generator: Convert periodic cron tasks to systemd timers.
- URL Encoder: Encode URL parameters and URI paths.
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-LocationWindows (CMD / PowerShell)
:: Test NGINX configuration syntax in Windows
nginx.exe -t -c C:\nginx\conf\nginx.confPython
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/");
}
}
}