Nginx http_addition_filter_module 响应内容中追加内容

网友投稿 712 2022-09-27

Nginx http_addition_filter_module 响应内容中追加内容

Nginx http_addition_filter_module 响应内容中追加内容

addition_filter_module

The ​​ngx_is a filter that adds text before and after a response. This module is not built by default, it should be enabled with the ​​--with-parameter.

Example Configuration

./configure --prefix=/usr/local/nginx  --with-/ { add_before_body /before_action; add_after_body /after_action; }

ngx_在响应之前或者之后追加文本内容,比如想在站点底部追加一个 js 或者 css,可以使用这个模块来实现,这个模块和淘宝开发的 nginx footer 模块有点类似,但是还是有不同. 这个模块需要依赖子请求, nginx footer 依赖 nginx 写死的配置.

这个模块可以在我们原始返回给用户的响应中,响应之前和之后添加一些不同的内容。添加的方式是在响应的之前或者响应之后添加内容,而不是修改响应的本身。添加内容的方式是通过添加子请求,根据这个子请求返回的响应再添加到原始响应的前和后

ngx_add_before_body uri;默认值: —配置段: server, location发起一个子请求,请求给定的 uri,并且将内容追加到主题响应的内容之前。语法: add_after_body uri;默认值: —配置段: server, location发起一个子请求,请求给定的 uri,并且将内容追加到主题响应的内容之后。语法: addition_types mime-type …;默认值: addition_types text/html;配置段: server, location这个指令在 0.7.9 开始支持,指定需要被追加内容的 MIME 类型,默认为“ text/html”,如果制定为*,那么所有的

举例说明

第一个例子:[root@nginx-1.16.1]# cat objs/ngx_modules.c | grep extern ngx_module_t ngx_ &ngx_ "ngx_]# mkdir -p /data/]# echo "body" >> /data/server { listen 80; server_name test.com; charset utf-8; root /data/ location /{ # add_before_body /before_action; #先注释掉来看看 # add_after_body /after_action; # addition_types *; } location /before_action{ return 200 'new content before\n'; } location /after_action{ return 200 'new content after\n'; } }[root@]# curl test.com/a.txt --这是不使用add指令返回结果body-----------------------------------------------------------------------------------------location /{ add_before_body /before_action; add_after_body /after_action; addition_types *; } location /before_action{ #这个url可以使用反向代理去访问第三方服务,这里为了简单使用简单的return指令返回 return 200 'new content before\n'; } location /after_action{ return 200 'new content after\n'; }[root@nginx-1.16.1]# curl test.com/a.txt --可以看到在内容前后添加了相应的内容new content beforebodynew content after

第二个例子:来源于网络配置nginx.conf:server {listen 80;server_name ttlsa.com;root /data/site/ttlsa.com;location / {add_before_body /2013/10/header.html;add_after_body /2013/10/footer.html;}}测试:以下三个文件,对应请求的主体文件和 add_before_body、 add_after_body 对应的内容cat /data/site/test.ttlsa.com/2013/10/20131001_add.htmlI am titlengx_/data/site/test.ttlsa.com/2013/10/header.htmlI am header!cat /data/site/test.ttlsa.com/2013/10/footer.htmlfooter – ttlsa访问结果如下,可以看到 20131001_add.html 的顶部和底部分别嵌入了子请求 header.html 和 footer 的内容。curl test.ttlsa.com/2013/10/20131001_add.htmlI am header!I am titlengx_- ttlsa

addition 模块与nginx sub 替换响应内容模块应用场景有点相同,具体怎么使用,大家结合实际情况来使用。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Redis AOF文件校验
下一篇:Nginx http_secure_link_module 实现下载防盗链
相关文章

 发表评论

暂时没有评论,来抢沙发吧~