Skip to content
Nginx

Location Rules

Match request URIs with prefix, regex, and exact locations.

By EZ4Code Team
locationroutingregex

Code

server {
    listen 80;

    # Exact match - highest priority
    location = /favicon.ico {
        return 204;
        access_log off;
    }

    # Prefix match - longest wins
    location /static/ {
        root /var/www;
        expires 30d;
    }

    # Case-insensitive regex
    location ~* \.(jpg|png|gif|svg)$ {
        root /var/www/images;
    }

    # Case-sensitive regex (evaluated in order)
    location ~ ^/api/v[0-9]+/ {
        proxy_pass http://api;
    }

    # Named location for internal redirects
    location @fallback {
        proxy_pass http://legacy;
    }

    location / {
        try_files $uri $uri/ @fallback;
    }
}

Explanation

Nginx evaluates location blocks in a defined priority: exact (=) first, then prefix matches by length, then regex (~ and ~*) in declaration order. The first matching regex wins, so order matters. Named locations (@name) act as internal targets reachable only via try_files or error_page.

More Nginx Snippets