利用headers_more模块修改HTTP头部


模块简介

nginxheaders_more 模块用于 添加、修改或清除 请求/响应头,该模块不是 nginx 自带的,默认不包含该模块,需要另外安装。幸运的是 openresty 默认包含了该模块,可以直接使用。

  • 该模块主要有4个指令
    • more_set_headers 用于 添加、修改、清除 响应头

    • more_clear_headers 用于 清除 响应头

    • more_set_input_headers 用于 添加、修改、清除 请求头

    • more_clear_input_headers 用于 清除 请求头


模块添加

由于该模块 Nginx 官方版本默认不带,需要在编译过程手动添加,以下主要说明添加方法:

cd /opt/
git clone git@github.com:openresty/headers-more-nginx-module.git

cd ${Nginx源码目录}

# 添加模块,其余参数根据实际情况自行追加
./configure --prefix=/usr/local/nginx --add-module=/opt/headers-more-nginx-module

make

# 如需热更新,则无需执行make install
make install

模块验证

[root@test~]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.18.0
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-23) (GCC)
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx ...{省略其它参数}... --add-module=/opt/headers-more-nginx-module

以下是使用示例

1. 删除响应头

去掉 X-Powered-By 和 Server 响应头:

more_clear_headers X-Powered-By Server;

删除前:

删除后:

2. 自定义 / 覆盖 响应头

去掉 X-Powered-By 响应头,增加一个 X-Author 响应头,修改 Server 响应头为 Apache ,伪装一下。

more_clear_headers X-Powered-By;
more_set_headers "X-Author: Lcy" "Server: Apache 2.4";

效果:

  • 覆盖方式同理,只需直接添加

    more_set_headers "X-Author: Lcy" "Server: Apache 2.4";

    即可覆盖 X-AuthorServer 的响应头值。

3. 修改请求头

把 query_string 中的 cid 参数改写成 Cookie

if ($arg_cid) {
  more_set_input_headers "Cookie: PHPSESSID=$arg_cid";
}

效果如下:


参考链接

该模块的详细文档可参考 headers-more-nginx-module

https://blog.csdn.net/chunyuan314/article/details/81737303


文章作者: NesteaLin
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 NesteaLin !
  目录