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

nginx lua 配合使用时的注意事项(汇总)

2015-04-10 00:39 337 查看
最近项目中使用到了nginx + lua 扩展方式来访问数据库。 其他服务向其发送HTTP请求获取数据。

在处理header 时有了一些问题,纠结了一阵子,最终解决了。

nginx 默认对 HTTP 协议的请求 header 进行合格检查,比如,header不能有下划线等,所以如果你要携带自定义的header 头,其格式写法最好和内置的保持一致,即最好用短横线 - 代替 下划线 _ ,
如果非要用下划线,那么需要配置 指令(http 或server下)

ignore_invalid_headers off; 是否忽略掉不合格的header域 默认是,

underscores_in_headers on; 是否允许 header 域 使用下划线


如果要在lua中 进行输出返回包的 header 域时, 若要输出带下划线的域,可以配置指令(在 http下)

lua_transform_underscores_in_response_headers off; 默认是开启的,那么nginx lua 会将 下划线转换为 短横; 配置关闭后,则不自动做转换。

如果觉得nginx默认的日志 时间戳很难看,那么可以在 配置文件中指定如下:

env TZ=UTC;

那么 时间格式 将变为 如 2015/02/10 14:05:21 , 即iso格式。

如果nginx lua 返回的包头,没有包含 Content-length 字段,那么在字段中可以显式指定下,输出中就会生效。

local ngx_return=function(data,code,err)
--ngx.status=code
local ret={}
ret.data=data
ret.code=code
ret.err=err
local jrt=cjson.encode(ret)
ngx.header["Server"]=nil
ngx.header["Date"]=nil
--ngx.header["Connection"]= nil
-- ngx.header["Connection"]="Keep-Alive"
ngx.header["correlation_id"]=ngx.req.get_headers()["correlation_id"]
<strong>    ngx.header["Content-Length"] = string.len(jrt)</strong>
ngx.say(jrt)
ngx.flush(true)
ngx.log(ngx.INFO,"return client ret=",jrt)
--to cause quit the whole request rather than the current phase handler
return ngx.exit(ngx.HTTP_OK)
end


关于nginx header 下划线处理指令,详细介绍如下


lua_transform_underscores_in_response_headers

syntax: lua_transform_underscores_in_response_headers on|off
default: lua_transform_underscores_in_response_headers on
context: http, server, location, location-if
Controls whether to transform underscores (
_
) in the response header names specified
in the ngx.header.HEADER API to hypens (
-
).
This directive was first introduced in the
v0.5.0rc32
release.

underscores_in_headers


Syntax:
underscores_in_headers on
|
off
;

Default:
underscores_in_headers off;

Context:
http
,
server


Enables or disables the use of underscores in client request header fields. When the use of underscores is disabled, request header fields whose names contain underscores are marked as invalid and become subject to the ignore_invalid_headers directive.
If the directive is specified on the server level,
its value is only used if a server is a default one. The value specified also applies to all virtual servers listening on the same address and port.


ignore_invalid_headers


Syntax:
ignore_invalid_headers on
|
off
;

Default:
ignore_invalid_headers on;

Context:
http
,
server


Controls whether header fields with invalid names should be ignored. Valid names are composed of English letters, digits, hyphens, and possibly underscores (as controlled by the underscores_in_headers directive).
If the directive is specified on the server level, its value is only used if a server is a default
one. The value specified also applies to all virtual servers listening on the same address and port.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: