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的字段中帶下劃線

重啓,解決。

相關文章
相關標籤/搜索