0
0
NginxConceptBeginner · 3 min read

Prefix Match Location in Nginx: How It Works and When to Use

In Nginx, a prefix match location is a way to match request URLs that start with a specific string. It uses the location /path syntax to route requests whose paths begin with that prefix. This method is simple and fast for matching URL beginnings without complex patterns.
⚙️

How It Works

Think of prefix match location in Nginx like sorting mail by street name. If you want to deliver letters to all houses on "Main Street," you look for addresses starting with "Main Street." Similarly, Nginx checks if the requested URL path starts with the prefix you set.

When a request comes in, Nginx compares the URL path against all location blocks. If it finds a prefix match, it uses that block to handle the request. This is faster than complex pattern matching because it just checks the start of the string.

For example, location /images matches any URL starting with /images, like /images/cat.jpg or /images/icons/logo.png. This makes it easy to serve static files or route groups of URLs.

💻

Example

This example shows a prefix match location that serves static files from the /images URL path.

nginx
server {
    listen 80;
    server_name example.com;

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

    location / {
        proxy_pass http://backend;
    }
}
Output
Request to http://example.com/images/photo.jpg serves file /var/www/static/images/photo.jpg Request to http://example.com/other goes to backend server
🎯

When to Use

Use prefix match locations when you want to route all requests starting with a certain path to a specific handler. This is common for serving static content like images, CSS, or JavaScript files.

It is also useful when you want to separate API endpoints or admin pages by URL prefix, making your configuration clear and efficient.

For example, you might use location /api to forward API requests to a backend service, while other requests go elsewhere.

Key Points

  • Prefix match uses location /prefix syntax to match URL starts.
  • It is simple and fast because it checks only the beginning of the path.
  • It is ideal for grouping related URLs like static files or API routes.
  • More specific prefix matches take priority over less specific ones.

Key Takeaways

Prefix match location in Nginx routes requests based on URL path beginnings using simple string matching.
Use prefix match to efficiently serve static files or group related URL paths like APIs.
Prefix matches are faster than regex and are prioritized by specificity.
Define prefix locations with syntax like location /prefix for clear routing rules.