您的位置:首页 > 运维架构 > Nginx

nginx代理 修改响应内容

2015-09-14 15:07 621 查看
最近接手一个问题
在每次出现404的情况时:需要在响应的内容中,添加 request_uri remote_ip 等一些内容。
开始的时候 发现一个模块 --with-http_sub_module 可以对响应内容进行一个替换修改
但是这个模块需要从新对nginx进行编译,在编译的时候添加模块
--prefix=/usr/local/nginx  --with-http_sub_module
然后就可以在nginx.conf中使用了

sub_filter thisisatestipaddr 'ipaddr:$remote_addr \nrequest_url:$server_name$request_uri \nstatus:$status';
sub_filter_types *;
sub_filter_once on;

但是由于我的nginx不是做web的,他是用来做代理的。而且还不想在后端web服务器上指定404页面,找到一个模块 error_page可以指定404页面跳转,但是在nignx做代理的情况下error_page 不生效。后来发现在location下添加
proxy_intercept_errors on;
proxy_redirect default;

proxy_intercept_errors语法:proxy_intercept_errors [ on|off ]
默认值:proxy_intercept_errors off
使用字段:http, server, location
使nginx阻止HTTP应答代码为400或者更高的应答。
默认情况下被代理服务器的所有应答都将被传递。
如果将其设置为on则nginx会将阻止的这部分代码在一个error_page指令处理,如果在这个error_page中没有匹配的处理方法,则被代理服务器传递的错误应答会按原样传递。

并且把404跳转重新指定一个模块就可以了。整体的配置如下:
http{
fastcgi_intercept_errors on; #启用error_page

server{
error_page 404 /404.html; #指定跳转页面
location = /404.html { #页面存放在本地的目录
root html;
sub_filter thisisatestipaddr 'ipaddr:$remote_addr \nrequest_url:$server_name$request_uri \nstatus:$status';
sub_filter_types text/html;
sub_filter_once on;
}
location /{
proxy_pass http://www.zhao.com; proxy_intercept_errors on;
proxy_redirect default;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: