header_filter_by_lua的说明:
header_filter_by_lua
syntax: header_filter_by_lua <lua-script-str>
context: http, server, location, location if
phase: output-header-filter
WARNING Since the v0.9.17 release, use of this directive is discouraged; use the new header_filter_by_lua_block directive instead.
Uses Lua code specified in <lua-script-str> to define an output header filter.
Note that the following API functions are currently disabled within this context:
Output API functions (e.g., ngx.say and ngx.send_headers)
Control API functions (e.g., ngx.redirect and ngx.exec)
Subrequest API functions (e.g., ngx.location.capture and ngx.location.capture_multi)
Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
Here is an example of overriding a response header (or adding one if absent) in our Lua header filter:
location / {
proxy_pass http://mybackend;
header_filter_by_lua 'ngx.header.Foo = "blah"';
}
This directive was first introduced in the v0.2.1rc20 release.
官网:https://github.com/openresty/lua-nginx-module#header_filter_by_lua
作用:
a)新增自定义的HTTP头
b)重新设置upstream返回的HTTP头,也就是起到覆盖作用
使用示范源码:nginx.conf
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
log_format main '$msec $status $request $request_time '
'$http_referer $remote_addr [ $time_local ] '
'$upstream_response_time $host $bytes_sent '
'$request_length $upstream_addr';
access_log logs/access.log main buffer=32k flush=1s;
upstream remote_world {
server 127.0.0.1:8080;
}
server {
listen 80;
location /exec {
content_by_lua '
local cjson = require "cjson"
local headers = {
["Etag"] = "663b92165e216225df78fbbd47c9c5ba",
["Last-Modified"] = "Fri, 12 May 2016 18:53:33 GMT",
}
ngx.var.my_headers = cjson.encode(headers)
ngx.var.my_upstream = "remote_world"
ngx.var.my_uri = "/world"
ngx.exec("/upstream")
';
}
location /upstream {
internal;
set $my_headers $my_headers;
set $my_upstream $my_upstream;
set $my_uri $my_uri;
proxy_pass http://$my_upstream$my_uri;
header_filter_by_lua '
local cjson = require "cjson"
headers = cjson.decode(ngx.var.my_headers)
for k, v in pairs(headers) do
ngx.header[k] = v
end
';
}
}
server {
listen 8080;
location /world {
echo "hello world";
}
}
}
运行:openresty -p `pwd` -c conf/nginx.conf
运行结果:
原文出自:http://blog.csdn.net/daiyudong2020/article/details/53149242
End;