Nginx反向代理多路径映射至后端单路径的Rewrite规则问题
Let's break down what's happening here and fix your Nginx config issues step by step.
Why you're seeing those errors
Rewrite cycle error: When you used
rewritewithout any flags, Nginx triggers an internal redirect after rewriting the URL. The rewritten path/static/$2ends up matching your originallocation ~ ^/(static|images)/(.*)$block again, creating an infinite loop—hence the "rewrite or internal redirection cycle" message.Local file lookup instead of proxying: When you switched the backend path to
k-static, your rewrite produced a URL like/k-static/assents/p388.img. But your location block only matches URLs starting with/static/or/images/, so this rewritten path doesn't hit your proxy location at all. Nginx falls back to its default server behavior, using therootdirective (in your case,/var/www/html) to look for the file locally—leading to the "No such file or directory" error pointing to your local filesystem.
Solutions to achieve your goal
Fix 1: Use rewrite ... break to avoid cycles and force proxying
Add the break flag to your rewrite rule. This tells Nginx to stop processing further location matches after the rewrite, so it'll use the current location's proxy_pass instead of looping or falling back to local files:
location ~ ^/(static|images)/(.*)$ { rewrite ^/(static|images)/(.*)$ /static/$2 break; proxy_pass http://server:8080; }
If you want to use k-static as the backend path instead, just adjust the rewrite target:
location ~ ^/(static|images)/(.*)$ { rewrite ^/(static|images)/(.*)$ /k-static/$2 break; proxy_pass http://server:8080; }
Fix 2: Skip rewrite entirely (cleaner and more efficient)
Your original config was actually already doing exactly what you want, without needing a rewrite at all. It's concise and avoids the overhead of rewrite rules:
location ~ ^/(static|images)/(.*)$ { proxy_pass http://server:8080/static/$2; }
This directly maps any request starting with /static/ or /images/ to /static/$2 on your backend server—no loops, no local file lookups. It's the most efficient way to handle this scenario.
内容的提问来源于stack exchange,提问作者donnie

