BudiBadu Logo
Samplebadu

Nginx Config by Example: Location Blocks

Nginx 1.x

Routing requests based on URI patterns with this code example showing location block modifiers for exact match, prefix match, case-sensitive regex, and case-insensitive regex with priority-based selection algorithm.

Code

server {
    listen 80;
    server_name example.com;

    # 1. Exact match (=)
    # Matches only /exact
    location = /exact {
        return 200 "Exact match";
    }

    # 2. Prefix match (default)
    # Matches /images/cat.png, /images/icon.ico
    location /images/ {
        root /var/www/data;
    }

    # 3. Regex match (~)
    # Case-sensitive match for .php files
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
    }

    # 4. Case-insensitive regex match (~*)
    # Matches .jpg, .JPG, .png, etc.
    location ~* \.(jpg|jpeg|png|gif)$ {
        expires 30d;
    }
}

Explanation

Location blocks reside within server blocks and specify how Nginx processes requests for specific URLs or URL patterns, enabling different behaviors for various parts of a website. Location directives use modifiers to control URI matching behavior, with Nginx following a specific selection algorithm to determine which location block handles each request.

Location matching modifiers include:

  • = exact match modifier matches URI exactly and stops searching immediately
  • No modifier creates prefix match, matching URIs starting with specified string
  • ^~ prefix match modifier stops regex checking if this is longest prefix match
  • ~ case-sensitive regular expression match
  • ~* case-insensitive regular expression match

Nginx's location selection algorithm prioritizes exact matches first, then remembers the longest prefix match before checking regex matches in order of appearance. If a regex match is found, it is used; otherwise, the remembered prefix match is selected. This algorithm enables flexible routing configurations with predictable behavior. The ^~ modifier provides an optimization by preventing regex evaluation when the longest prefix match uses this modifier.

Code Breakdown

7
location = /exact exact match stops search immediately if URI matches.
13
location /images/ prefix match for URIs starting with /images/.
19
location ~ \.php$ case-sensitive regex matches URIs ending in .php.
25
~* case-insensitive regex matches .jpg, .JPG, .Jpg variations.