How to Proxy Based on Path in Nginx: Simple Guide
To proxy requests based on path in
nginx, use the location directive to match the path and the proxy_pass directive to forward requests to the target server. Each location block can specify a different backend URL to proxy requests depending on the path prefix.Syntax
The basic syntax to proxy based on path in nginx uses the location block to match URL paths and the proxy_pass directive to forward requests.
location /path/ { ... }: Matches requests starting with/path/.proxy_pass http://backend/;: Forwards matching requests to the backend server.
Inside the location block, you can add other proxy settings like headers or timeouts.
nginx
location /path/ {
proxy_pass http://backend/;
}Example
This example shows how to proxy requests starting with /api/ to one backend server and requests starting with /images/ to another backend server.
nginx
server {
listen 80;
server_name example.com;
location /api/ {
proxy_pass http://api_backend/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /images/ {
proxy_pass http://images_backend/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location / {
root /var/www/html;
index index.html;
}
}Output
When a user visits http://example.com/api/users, the request is forwarded to http://api_backend/users.
When a user visits http://example.com/images/logo.png, the request is forwarded to http://images_backend/logo.png.
Requests to other paths serve static files from /var/www/html.
Common Pitfalls
Common mistakes when proxying based on path include:
- Forgetting the trailing slash in
proxy_passwhich can cause incorrect URL forwarding. - Not setting necessary headers like
HostandX-Real-IP, which can break backend logic. - Using
location = /pathinstead oflocation /path/when you want to match all subpaths.
Example of wrong and right proxy_pass usage:
nginx
location /app/ {
# Wrong: missing trailing slash causes path duplication
proxy_pass http://backend/app/;
}
location /app/ {
# Right: trailing slash ensures correct path forwarding
proxy_pass http://backend/;
}Quick Reference
| Directive | Purpose | Example |
|---|---|---|
| location | Matches request path | location /api/ { ... } |
| proxy_pass | Forwards request to backend | proxy_pass http://backend/; |
| proxy_set_header | Sets headers for backend | proxy_set_header Host $host; |
| listen | Defines server port | listen 80; |
| server_name | Defines domain name | server_name example.com; |
Key Takeaways
Use
location blocks to match URL paths for proxying in Nginx.Always include a trailing slash in
proxy_pass to avoid URL path issues.Set headers like
Host and X-Real-IP to preserve client info.Test your config with
nginx -t before reloading to catch syntax errors.Use separate
location blocks for different paths to proxy to different backends.