worker_processes 4;error_log logs/error.log;events { worker_connections 1024;}http { lua_package_path "./lua/?.lua;;";
#Basic reverse proxy server upstream backend{ #server "mention IP of hostname or hostname" server 0.0.0.0:5000; }
server { listen 8080;
lua_code_cache off; # for development only
location / { #default_type text/html; #content_by_lua_file ./lua/nginx_ss.lua;
header_filter_by_lua 'ngx.header.content_length = nil';
body_filter_by_lua_file ./lua/filterbody.lua;
} }}
############################## filterbody.lua contains
replacestr = "<script>here you go</script></head>";
ngx.arg[1] = ngx.re.sub(ngx.arg[1],"</head>", replacestr);
What is the role of ngx.arg[1] and ngx.arg[2] ? <script type="text/javascript">
var __uzdbm_a = "asdasd-asdsad-1232asd-12312--asdasd";
</script>
ngx.location.capture("api/call_remote_server", { method = ngx.HTTP_POST, body = final_json ).--------------Nginx.conf---------------
location / { access_by_lua_file ./lua/nginx_ss.lua; #echo "Demonic World";
proxy_pass http://127.0.0.1:8000/$request_uri;
sub_filter '<script type="text/javascript">var i = 10;</script></body>' '</body>'; sub_filter_once on; sub_filter_types text/html;
#header_filter_by_lua ' #ngx.header.content_length = nil #'; #body_filter_by_lua_file ./lua/js_ss.lua;
}
---------------------- js_ss.lua -------------------------------
local ss_script = "<script type=\"text/javascript\">var i = 10;</script></body>"
--print(ss_script);
local chunk, eof = ngx.arg[1], ngx.arg[2]local buffered = ngx.ctx.bufferedif not buffered then buffered = {} -- XXX we can use table.new here ngx.ctx.buffered = bufferedendif chunk ~= "" then buffered[#buffered + 1] = chunk ngx.arg[1] = nilendif eof then local whole = table.concat(buffered) ngx.ctx.buffered = nil whole = string.gsub(whole, ss_script, "</body>") ngx.arg[1] = wholeend
I have tried both method but i am not able to append the JS to response body.. Please point my errors here and i cant add any other dependency it has to be in lua openresty domain! Thanks.
Thanks agentzh, ofcourse yeah first string then replacement that's an order. How did i did silly mistakes. Stupid huh!
But in 2nd using filter body in lua, I need to append the JavaScript in response DOM, it is dynamic in every call. It will be better if I can add js in <head> tag of response body.
<script type="text/javascript">
var i = 10; //varying
</script>
So I followed some of early threads regarding response changing and found your chunk buffering n then applying replacement to get guaranteed response change. But its also not working. Help me out.
Sub_filter only filters and allow change inside <body> tag elements not with <head> and <body> replacement itself.