How to Use Location in Nginx: Syntax, Examples, and Tips
In Nginx, the
location directive defines how to process requests for specific URL patterns inside a server block. You use location to match request URIs and specify actions like serving files or proxying requests.Syntax
The location directive is used inside a server block to match request URIs. It has this basic form:
location [modifier] /uri/ { ... }
Modifiers control how the URI is matched:
=for exact match~for case-sensitive regex match~*for case-insensitive regex match^~for prefix match with higher priority- No modifier means prefix match
The block contains configuration for handling matched requests.
nginx
location [modifier] /uri/ {
# configuration
}Example
This example shows how to serve static files from /var/www/html for requests to /static/, and proxy API requests starting with /api/ to a backend server.
nginx
server {
listen 80;
server_name example.com;
location /static/ {
root /var/www/html;
}
location /api/ {
proxy_pass http://localhost:3000/;
}
location = / {
return 200 'Welcome to the homepage!';
}
}Output
When accessing http://example.com/static/image.png, Nginx serves /var/www/html/static/image.png.
When accessing http://example.com/api/users, Nginx forwards the request to http://localhost:3000/users.
When accessing http://example.com/, Nginx returns 'Welcome to the homepage!' with HTTP 200.
Common Pitfalls
Common mistakes when using location include:
- Using prefix match without
^~when regex locations exist, causing unexpected matches. - Forgetting the trailing slash in
proxy_pass, which changes the forwarded URI. - Overlapping locations without clear priority, leading to confusion about which block handles a request.
Always test your location blocks to ensure the correct one matches.
nginx
location /api/ {
proxy_pass http://backend/;
}
location /api/v1/ {
proxy_pass http://backend/v1/;
}
# Wrong: The /api/ block may override /api/v1/ if not careful.
# Right:
location ^~ /api/v1/ {
proxy_pass http://backend/v1/;
}
location /api/ {
proxy_pass http://backend/;
}Quick Reference
| Modifier | Meaning | Example |
|---|---|---|
| = | Exact match | location = /exact { ... } |
| ~ | Case-sensitive regex | location ~ ^/images/.*\.jpg$ { ... } |
| ~* | Case-insensitive regex | location ~* \.(jpg|png)$ { ... } |
| ^~ | Prefix match with priority | location ^~ /static/ { ... } |
| (none) | Prefix match | location /images/ { ... } |
Key Takeaways
Use
location inside server blocks to match request URIs and define handling rules.Choose the right modifier (=, ~, ~*, ^~, or none) to control how Nginx matches URLs.
Remember that regex locations have lower priority than exact and ^~ prefix matches.
Always include trailing slashes carefully in
proxy_pass to control URI forwarding.Test your location blocks to avoid unexpected request routing.