使用Nginx+lua返回错误码并且返回自定义内容。

使用Nginx+lua返回错误码并且返回自定义内容。 
使用ngx.exit(后端服务返回的httpcode),如果后台返回的是500 等错误码的时候如下用法会有错误:

ngx.say(res.content)
ngx.exit(res.httpCode);
  •  

上面的代码在后端服务器返回非200的时候,会返回客户端 200,内容则是错误信息;日志显示大体是:在返回200之后,又设置成500 。

ngx.status = res.httpCode;
ngx.say(res.content);
ngx.exit(200);
  •  

上面的代码,会返回 500错误码和后端app返回的错误信息; 
结论: 
ngx.status 是设置http 相应码的。 
ngx.exit(code):官方文档如下

ngx.exit

syntax: ngx.exit(status)

context: rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, ngx.timer., balancer_by_lua, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*

When status >= 200 (i.e., ngx.HTTP_OK and above), it will interrupt the execution of the current request and return status code to nginx.

When status == 0 (i.e., ngx.OK), it will only quit the current phase handler (or the content handler if the content_by_lua* directive is used) and continue to run later phases (if any) for the current request.

The status argument can be ngx.OK, ngx.ERROR, ngx.HTTP_NOT_FOUND, ngx.HTTP_MOVED_TEMPORARILY, or other HTTP status constants.

To return an error page with custom contents, use code snippets like this:

 ngx.status = ngx.HTTP_GONE
 ngx.say("This is our own content")
 -- to cause quit the whole request rather than the current phase handler
 ngx.exit(ngx.HTTP_OK)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值