Nginx反向代理修改Request的HOST字段为什么会影响到sub filter替换Response的内容

1.尝试用Nginx反向代理公网上的网站cnki.net,并使用HttpSubstitution模块改写Response内容。当我配置proxy_set_header Host $host:$server_port 时,能够成功改写Response的内容;当我配置proxy_set_header Host cnki.net 时,改写不生效。我的疑问是,proxy_set_header Host改写的是Request的内容,为什么会影响我修改Response呢?

配置文件cnki.conf:

server {
   listen 8080;
   server_name zhongxiaocnki.net;
   include enable_ssl.conf;

   include cnki.net/rules/server-variable.conf;

### log files ###
   access_log logs/access.log;
   error_log logs/error.log debug;


   location / {
   proxy_pass http://www.cnki.net;                                      #这个一定要是https
   proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
   proxy_set_header Host $host:$server_port;
   #proxy_set_header Host www.cnki.net;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header X-Forwarded-Proto https;

   include cnki.net/rules/url_rewrite_rule.conf;
   include cnki.net/rules/redirect.conf;

}
}

配置文件url_rewrite_rule.conf:

sub_filter_once off;
sub_filter_types *;
sub_filter 'http://'  '$prtc://';
sub_filter 'www.cnki.net'  '$host:8080';
sub_filter 'piccache.cnki.net'  '$host:8081';
sub_filter 'kns.cnki.net'  '$host:8082';
sub_filter 'my.cnki.net'  '$host:8083';
sub_filter 'm.cnki.net'  '$host:8084';
sub_filter 'r.cnki.net'  '$host:8091';
sub_filter 'search.cnki.net'  '$host:8106';

当proxy_set_header Host $host:$server_port时的访问效果:

clipboard.png

当proxy_set_header Host www.cnki.net时的访问效果:

clipboard.png

问题:修改Request的HOST字段为什么会影响到sub filter替换Response的内容?

阅读 8.2k
1 个回答

知道原因了,跟我修改Request的HOST字段没有直接关系,问题在gzip上。

当我设置HOST为代理服务器自身时,cnki.net服务器返回Response时不会使用gzip压缩,请求头和返回头如下:

clipboard.png

当我设置HOST为www.cnki.net时,cnki.net服务器返回Response时采用gzip压缩内容,请求头和返回头如下:

clipboard.png

因为内容被gzip压缩过,因此无法按照预期的规则来替换。只需要在配置中加上:

proxy_set_header Accept-Encoding "";

通过这样的方式禁用gzip后,sub filter工作就正常了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题