Location Syntax
location [modifier] pattern { ... }
Modifiers
| Modifier |
Description |
Priority |
| = |
Exact match |
1 (highest) |
| ^~ |
Prefix match (stops regex search) |
2 |
| ~ |
Case-sensitive regex |
3 |
| ~* |
Case-insensitive regex |
3 |
| (none) |
Prefix match |
4 (lowest) |
Matching Priority
# 1. Exact match (=) - Highest priority
location = /favicon.ico {
log_not_found off;
}
# 2. Preferential prefix (^~)
location ^~ /images/ {
# Won't check regex if this matches
}
# 3. Regex (~ or ~*)
location ~* \.(jpg|jpeg|png|gif)$ {
expires 30d;
}
# 4. Prefix match (no modifier)
location /api/ {
proxy_pass http://backend;
}
# 5. Default (/)
location / {
try_files $uri $uri/ =404;
}
Common Patterns
Static Files
# Images with caching
location ~* \.(jpg|jpeg|png|gif|ico|svg|webp)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# CSS/JS with caching
location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public";
}
# Fonts
location ~* \.(woff|woff2|ttf|eot|otf)$ {
expires 365d;
add_header Access-Control-Allow-Origin *;
}
API Proxy
location /api/ {
proxy_pass http://localhost:3000/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
PHP-FPM
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/var/run/php/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors on;
}
Deny Access
# Deny hidden files
location ~ /\. {
deny all;
}
# Deny sensitive files
location ~* \.(env|log|sql)$ {
deny all;
}
# Deny directory listing
location /uploads/ {
autoindex off;
}
try_files Directive
# Try file, then directory, then 404
location / {
try_files $uri $uri/ =404;
}
# SPA routing (React, Vue, Angular)
location / {
try_files $uri $uri/ /index.html;
}
# Named location fallback
location / {
try_files $uri @backend;
}
location @backend {
proxy_pass http://localhost:3000;
}
intermediate | Core Concepts | Updated 2025-01-15
- nginx
- location
- routing
- matching
- regex