Description
This guide explains how to configure Nginx to forward requests from one server to another while maintaining the correct URL structure. It covers key concepts such as using proxy_pass, handling path modifications, and ensuring smooth request forwarding. Additionally, it highlights common pitfalls like incorrect trailing slashes and how to avoid them. By following this guide, you can efficiently set up a reverse proxy for static content, APIs, or any other resources across different servers.
Configuration Breakdown
location ~ ^/cdn {
set $backend https://cloud.cdn.com;
proxy_pass $backend;
}
How It Works
1. Matching Requests for /static
The location ~ ^/static block applies to any request where the path starts with /static.
The ~ indicates that a regular expression is used (^/static ensures it matches from the beginning of the path).
2. Setting a Backend Variable
set $backend https://cloud.cdn.com;
Defines a variable $backend with the value https://cloud.cdn.com
.
This provides flexibility for modifying the backend dynamically in the future.
3. Proxying Requests
proxy_pass $backend;
This forwards requests matching /static to https://cloud.cdn.com
.
Example:
Request: https://sitea.com/static/image.png
Proxies to: https://cloud.cdn.com/static/image.png
The response is then returned to the original client.
Possible Issues & Fixes
1. Missing Trailing Slash in proxy_pass
If proxy_pass is set to https://cloud.cdn.com
without a trailing slash, it behaves as expected:
The request path remains unchanged.
Example:
Request: https://sitea.com/static/image.png
Proxies to: https://cloud.cdn.com/static/image.png
(✅ Expected)
2. Adding a Trailing Slash (/) in proxy_pass
If proxy_pass is https://cloud.cdn.com/
, Nginx replaces /static with /:
proxy_pass https://cloud.cdn.com/;
Example:
Request: https://sitea.com/static/image.png
Proxies to: https://cloud.cdn.com/image.png
(🚫 Incorrect if /static/ is required)
Correct Approach (If /static Must Be Included)
If cloud.cdn.com expects /static in the request, ensure:
proxy_pass https://cloud.cdn.com;
This keeps /static in the proxied request.
If cloud.cdn.com does not need /static, use:
proxy_pass https://cloud.cdn.com/;
This strips /static before forwarding.
Summary
Matches any request starting with /static.
Proxies to https://cloud.cdn.com
.
Ensure correct trailing slash usage in proxy_pass to maintain the intended request path.
Top comments (0)