You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Rewrite cycle error: When you used rewrite without any flags, Nginx triggers an internal redirect after rewriting the URL. The rewritten path /static/$2 ends up matching your original location ~ ^/(static|images)/(.*)$ block again, creating an infinite loop—hence the "rewrite or internal redirection cycle" message.

  2. 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 the root directive (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:42:35