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

首先,我先说下我使用的是lnmp一键安装中的nginx。php

如今进入正题:html

nginx

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

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

fastcgi_intercept_errors on;

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

而后后端

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

将server块内的error_page前的注释去掉(也就是#号),通常来讲,后端程序挂掉后会返回502错误超时页面,具体是多少看具体状况,我就拿502作示例。将注释去掉以后,在后面加上502 /502.json,而且跟上502.json文件所在的目录,以下。dom

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串。code

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

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的字段中带下划线

重启,解决。

相关文章
相关标签/搜索