Exact Match Location in Nginx: What It Is and How It Works
exact match location is defined by a location block starting with =, which matches the requested URL exactly without any pattern or prefix matching. This means Nginx will only use this block if the URL path is an exact match, providing precise control over request handling.How It Works
Imagine you have a mail sorter who only delivers letters to a specific house number, ignoring all others. In Nginx, an exact match location works similarly by matching the URL path exactly as specified, without considering any additional characters or patterns.
When Nginx receives a request, it checks location blocks in a specific order. If it finds an exact match location (marked with =), it immediately uses that block to handle the request. This prevents other more general location blocks from being used, ensuring precise routing.
This is useful when you want to serve a specific page or resource only when the URL matches exactly, avoiding accidental matches with similar URLs.
Example
This example shows an exact match location that serves a special page only when the URL is exactly /special. Other URLs starting with /special will not use this block.
server {
listen 80;
location = /special {
return 200 'This is the exact match for /special';
}
location /special {
return 200 'This is a prefix match for /special and anything after';
}
}When to Use
Use exact match locations when you need to handle a specific URL path differently from all others. For example:
- Serving a unique landing page at a precise URL.
- Handling a special API endpoint that should not match similar paths.
- Overriding general location blocks for a single URL.
This helps avoid unexpected behavior from prefix or regex matches and gives you clear control over routing.
Key Points
- Exact match locations start with
=in Nginx configuration. - They match the URL path exactly, no more, no less.
- They have the highest priority and stop further location searching.
- Useful for precise routing of specific URLs.
Key Takeaways
= to match URLs exactly.