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

本文介绍如何使用Nginx结合Lua来正确处理并返回错误码及自定义内容。通过设置ngx.status和使用ngx.exit,可以实现对客户端响应的精确控制,并确保返回正确的HTTP状态码和自定义错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值