Published on

NGINX location

In NGINX, a location block is used to define how requests for specific URIs should be processed. It is configured inside a server block.


Basic Syntax

server {
    listen 80;
    server_name example.com;

    location / {
        root /var/www/html;
        index index.html;
    }
}

🔹 Location Matching Types

NGINX selects a location block based on specific matching rules.

1️⃣ Prefix Match (Most Common)

location /images/ {
    root /data;
}
  • Matches any request starting with /images/
  • Example: /images/logo.png

2️⃣ Exact Match (=)

location = /favicon.ico {
    access_log off;
}
  • Matches exactly /favicon.ico
  • Highest priority

3️⃣ Regex Match (~ and ~*)

Case-Sensitive

location ~ \.php$ {
    fastcgi_pass unix:/run/php/php8.1-fpm.sock;
}

Case-Insensitive

location ~* \.(jpg|jpeg|png|gif)$ {
    expires 30d;
}

4️⃣ Prefix Match with ^~

location ^~ /static/ {
    root /var/www/static;
}
  • If this matches, NGINX stops searching regex locations
  • Useful for performance optimization

🔹 Location Selection Priority (Very Important)

NGINX follows this order:

  1. = (Exact match)
  2. ^~ (Prefix match, skip regex)
  3. Regex (~, ~*) — first match wins
  4. Longest prefix match (normal /path/)

🔹 Example (API + Static + PHP)

server {
    listen 80;
    server_name example.com;

    location = /health {
        return 200 "OK";
    }

    location ^~ /static/ {
        root /var/www/app;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    }

    location / {
        proxy_pass http://backend;
    }
}

🔹 Common Use Cases in AWS / GCP

Since you're working with AWS & GCP, common scenarios include:

Reverse Proxy to Backend (EC2, ECS, GKE)

location /api/ {
    proxy_pass http://backend-service;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

Health Check Endpoint (for ALB / GCP Load Balancer)

location = /health {
    access_log off;
    return 200 "healthy";
}

Serving Static Files from S3 (via proxy)

location /assets/ {
    proxy_pass https://my-bucket.s3.amazonaws.com;
}