请求Nginx配置帮助:带路径追加的域名转发与URL重写
Got it, let's get this proxy issue sorted out for you. The core problem here is that you need to rewrite the incoming request path from /downloads to /app/downloads while preserving query parameters, all while keeping the browser showing service1.com URLs.
Why Your Previous Config Failed
When you used proxy_pass $upstream_endpoint/app/$args;, a couple of key issues broke the expected behavior:
- Using a variable in
proxy_passchanges how Nginx handles URI rewriting—it won’t automatically replace the matched/downloadspath with your appended/app/segment - Adding
$argsdirectly to theproxy_passstring mangles the path structure, leading to upstream URLs like/app/?param1=ainstead of the intended/app/downloads?param1=a
Solution 1: Use rewrite for Variable Upstreams
If you need to keep using the $upstream_endpoint variable (for dynamic upstream targets), use a rewrite rule to explicitly adjust the request path before proxying:
location /downloads { set $upstream_endpoint https://service2.com; # Rewrite path: /downloads → /app/downloads, preserve any trailing segments rewrite ^/downloads(.*)$ /app/downloads$1 break; proxy_pass $upstream_endpoint; # Optional but recommended: Preserve original request headers for upstream proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
- The
rewriterule captures everything after/downloads(including an empty string) and appends it to/app/downloads breakstops further rewrite processing after this rule- Query parameters are automatically preserved by Nginx—no need to manually add
$args
Solution 2: Direct Path Mapping (Simpler for Fixed Upstreams)
If your upstream address is static, you can skip the variable and let Nginx handle path mapping automatically:
location /downloads { proxy_pass https://service2.com/app/downloads; # Same header preservation as above proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
- Here, Nginx replaces the matched
/downloadspath with/app/downloadsin the upstream request - Query parameters stay intact automatically, so
https://service1.com/downloads?param1=a¶m2=bwill correctly forward tohttps://service2.com/app/downloads?param1=a¶m2=b
Testing the Config
Always validate your Nginx config before restarting to avoid downtime:
nginx -t
If the test passes, restart Nginx to apply changes:
# For systemd-based systems (Ubuntu, RHEL 8+, etc.) systemctl restart nginx # For SysVinit systems service nginx restart
内容的提问来源于stack exchange,提问作者code1234

