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

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

2016-12-28 16:48 417 查看
使用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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐