您的位置:首页 > 运维架构 > 反向代理

nginx作json api反向代理,如何返回json形式的错误代码?(绝对有效)

2017-11-02 00:00 921 查看
首先,我先说下我使用的是lnmp一键安装中的nginx。

现在进入正题:



vim /usr/local/nginx/conf/nginx.conf

在http模块中的fastcgi_busy_buffers_size 128k下面加上

fastcgi_intercept_errors on;

注意,这里不要忘记分号。这句话是一定要加上的。



然后

vim /usr/local/nginx/conf/vhost/your domain conf file(你自己的域名配置文件)

将server块内的error_page前的注释去掉(也就是#号),一般来说,后端程序挂掉后会返回502错误超时页面,具体是多少看具体情况,我就拿502做示例。将注释去掉之后,在后面加上502 /502.json,并且跟上502.json文件所在的目录,如下。

location = /502.json {
root   /usr/local/nginx/html;
}

具体看截图。



error_page  502 /502.json;
include enable-php.conf;
location = /502.json { root /usr/local/nginx/html; }

记得要在/usr/local/nginx/html下建立你要修改的json文件,并且在里面加上你需要的json串。

建立完文件后,用/usr/local/nginx/sbin/nginx -t测试配置有无错误,没有错误会返回

nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

最后,记得重启nginx,/usr/local/nginx/sbin/nginx -s reload。

使用过程中发现,使用自定义带下划线的header头无效(在后台程序中打印出来的header信息中没有我们自定义的header头)。

解决方法如下:

将下面这段配置信息加入到http或者server块中,

underscores_in_headers on;

语法:underscores_in_headers on/off
默认值:off
使用字段:http, server
效果:是否允许在header的字段中带下划线

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