Aaron Lau(韩栖)

Nginx 学习笔记 (a3) —— 让 sub_filter 替换 Gzip 内容

368 字

在微信小程序 web-view 跳转外部链接?甲方的需求千奇百怪,好在办法总比困难多。不是只允许业务域名吗?此时反代不失为一个办法。就算绕开了限制,由于内容经你方服务器转发,你方也须承担责任。

先 proxy_pass,再用 sub_filter 把对方域名换成我方域名,避免打开非业务域名。可有些网站无视 Accept-Encoding: '',不管三七二十一,统统返回压过的,所以替换失败。先来看人家怎么办到的:对方 frontend 向 upstream 请求 gzip,backend 则把 gzip_http_version 设成 1.0(Nginx 默认以 HTTP/1.0 连接上游)。

思路清晰了有没有?先解压、再替换就好了呗。Maxim Dounin 写了个 gunzip filter 模块,还有人直接修改 Nginx 源码。另一种 trick(感谢 ryd994 大大的原帖)比较直观:做两次 proxy_pass,先反代源站 gzip 过的内容,再反代一次即可获得未压缩的内容。

location /forward {
    proxy_pass https://example.com;
    # proxy_set_header Accept-Encoding 'gzip';
    # gunzip on;
}

location / {
    proxy_pass https://yourdomain.com/forward;
    proxy_set_header Accept-Encoding '';

    sub_filter_types *;
    sub_filter_once off;
    sub_filter 'example.com' 'yourdomain.com';
}

上面的 gunzip on 和下面的 Accept-Encoding '' 互为替代。即使禁用压缩就能顺利替换,也可以试看看这招。这种需求很能吃出站流量,带宽嘛,总是省一点算一点。

<small>原载 App-scope,有删改。</small>

App-scope · 教程 · Nginx