Nginx sub_filter可动态替换反向代理响应体中的绝对路径以适配代理入口,需确保响应未压缩、显式设置sub_filter_types、关闭sub_filter_once、并注意匹配限制与常见陷阱。

可以通过 Nginx 的 sub_filter 指令在反向代理响应体中动态替换 HTML、CSS、JS 等文本内容里的绝对路径(如 https://cdn.example.com/ 或 /static/),使其适配当前代理入口的域名或路径,从而解决静态资源跨域、缓存失效或路径错位问题。
确保 sub_filter 生效的基本前提
sub_filter 默认只作用于 text/html 类型响应,且不处理压缩内容。需确认以下几点:
- 后端返回的响应头中
Content-Encoding为identity(未启用 gzip/brotli);若已压缩,需在 proxy 层先解压(用gunzip on或关闭后端压缩) - 显式设置
sub_filter_types才能处理text/css、application/javascript等类型 -
sub_filter是逐行匹配的,不支持正则,也不跨行;大块注释或换行可能影响替换效果 - 必须启用
sub_filter_once off才能全局替换所有匹配项(默认只替换第一个)
典型场景:将后端绝对路径重写为代理层相对路径
假设后端应用生成的 HTML 中含:<link rel="stylesheet" href="https://www.php.cn/link/8b63b93bbe10e6712a7ecfc86c7c735estatic/main.css">
而你通过 https://proxy.example.com/app/ 代理访问,希望改为:<link rel="stylesheet" href="/app/static/main.css">
配置示例如下:
location /app/ {
proxy_pass https://backend-app/;
proxy_set_header Host $host;
<pre class="brush:php;toolbar:false;"># 启用 sub_filter
sub_filter "https://www.php.cn/link/8b63b93bbe10e6712a7ecfc86c7c735e" "/app/";
sub_filter "http://app.example.com/" "/app/";
sub_filter_once off;
sub_filter_types text/html text/css application/javascript;
# 防止后端返回 gzip 导致 sub_filter 失效
proxy_http_version 1.1;
proxy_set_header Accept-Encoding "";
gunzip on;
# 可选:修正 Location 响应头中的跳转路径(与 sub_filter 无关,但常配套使用)
proxy_redirect https://www.php.cn/link/8b63b93bbe10e6712a7ecfc86c7c735e /app/;}
进阶技巧:结合变量实现动态路径注入
若代理路径由变量决定(如多租户子路径 /t1/、/t2/),可用 map + sub_filter 实现条件替换:
map $uri $upstream_host {
~^/t1/(.*)$ app-tenant1.example.com;
~^/t2/(.*)$ app-tenant2.example.com;
}
<p>map $uri $sub_path {
~^/t1/(.<em>)$ /t1/;
~^/t2/(.</em>)$ /t2/;
}</p><p>server {
location ~ ^/(t1|t2)/ {
proxy_pass <a href="https://www.php.cn/link/92732d8798add606646430bbd6748bfd">https://www.php.cn/link/92732d8798add606646430bbd6748bfd</a>;
sub_filter "<a href="https://www.php.cn/link/8b63b93bbe10e6712a7ecfc86c7c735e">https://www.php.cn/link/8b63b93bbe10e6712a7ecfc86c7c735e</a>" $sub_path;
sub_filter_once off;
sub_filter_types text/html text/css application/javascript;
...
}
}注意:sub_filter 不支持直接引用复杂变量(如嵌套 map 结果),建议用简单变量或预定义值,避免运行时解析失败。
常见陷阱与规避方式
-
响应体过大导致截断:Nginx 默认只缓存前 1MB 响应做 sub_filter,超长内容末尾不处理。可通过
sub_filter_last_modified on(需 1.13.5+)配合proxy_buffering on和增大proxy_buffers缓解 -
HTTPS 资源被浏览器阻止混合内容:若代理是 HTTPS,但 sub_filter 替换出
http://路径,浏览器会屏蔽。务必统一替换为/开头的相对路径或https://协议 -
JSON 或内联脚本中的路径误替换:sub_filter 无上下文识别能力,可能误改字符串字面量。可缩小
sub_filter_types范围,或让后端用占位符(如__ASSET_BASE__),再用 sub_filter 精准替换 -
字符编码不一致:确保后端响应头声明
charset=utf-8,且 sub_filter 替换内容编码相同,否则出现乱码或匹配失败
不复杂但容易忽略。关键是理清数据流向:后端输出 → Nginx 解压/缓冲 → sub_filter 扫描替换 → 发送给客户端。每一步都可能成为断点。

















