【发布时间】:2020-10-19 14:00:15
【问题描述】:
使用https://openresty.org/en/ 我有以下nginx.conf 文件
我正在尝试在 set_by_lua 部分的每个请求标头之间添加一个换行符 \n,然后将其输出到 access.log 文件。
http {
# Trying to see the request headers nicely in the access.log
# can't seem to get a nice line feed in from lua
log_format main '(ra:)$remote_addr - (ru:)$remote_user (time_local:)[$time_local] (request:)"$request" (status:)$status (bodybytessent:)$body_bytes_sent (http_referer)"$http_referer" (useragent:)"$http_user_agent" (xforward:)"$http_x_forwarded_for" \n(requestheaders:)$request_headers';
access_log logs/access.log main;
server {
listen 80;
server_name localhost;
location / {
set_by_lua $request_headers '
local h = ngx.req.get_headers()
local request_headers_all = ""
for k, v in pairs(h) do
# Here is the problem - the \n does not work
# just want to append a line feed to this string
request_headers_all = request_headers_all .. ""..k..": "..v..";" .. "\n"
end
return request_headers_all
';
root html;
index index.html index.htm;
}
...continued
错误是:
2020/06/29 11:36:04 [错误] 8204#8204: *25 未能加载内联 Lua 代码:set_by_lua:6: '"' 附近未完成的字符串
这行是问题所在:
request_headers_all = request_headers_all .. ""..k..": "..v..";" .. "\n"
所以这是某种逃避问题。 Lua ignore Escape Sequence 我迷路了。
基础操作系统是 Ubuntu 18.04。我正在尝试将这样的内容放入 access.log 文件中:
而不是这个:
(ra:)37.152.225.237 - (ru:)- (time_local:)[29/Jun/2020:11:47:46 +0000] (request:)"GET / HTTP/1.1" (status:)200 (bodybytessent:)422 (http_referer)"-" (useragent:)"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0" (xforward:)"-"
(requestheaders:)host: openrestytest836.westeurope.cloudapp.azure.com;accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8;upgrade-insecure-requests: 1;cache-control: no-cache;accept-language: en-GB,en;q=0.5;user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0;pragma: no-cache;connection: keep-alive;accept-encoding: gzip, deflate;
有很多方法可以做到这一点,但我很好奇如何将换行符放入 Lua 生成的字符串中。
【问题讨论】:
-
你试过使用
set_by_lua_block吗?set_by_lua已弃用。*_block指令没有转义问题:github.com/openresty/… -
顺便说一句,
table.insert+table.concat比重复连接更有效。