Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx lua set proxy headers

Tags:

nginx

proxy

lua

I believe this should be an easy find but for the life of me I cannot find an answer. I am trying to set proxy headers and I have tried the following ways:

location / {
        access_by_lua '
            ngx.header["ZZZZ"] = zzzzz
            proxy_pass http://127.0.0.1:8888;
        ';

OR

location / {
        access_by_lua '
            ngx.proxy_set_header["ZZZZ"] = zzzzz
            proxy_pass http://127.0.0.1:8888;
        ';

What is the correct way to set a proxy header.

Thank you stabiuti

like image 537
stabiuti Avatar asked Feb 08 '23 14:02

stabiuti


2 Answers

To set or clear headers being sent to proxy_pass, you can use following

to set headers, use

ngx.req.set_header(header_name, value)

to clear headers, use

ngx.req.clear_header(header)

to clear all headers, you can write

for header, _ in pairs(ngx.req.get_headers()) do
    ngx.req.clear_header(header)
end

Now to answer your question, you can use

location / {
        access_by_lua_block {
            ngx.req.set_header("ZZZZ", zzzzz)
        }
        proxy_pass http://127.0.0.1:8888;
}

Make sure to write it in access_by_lua or rewrite_by_lua.

like image 145
Himanshu Mishra Avatar answered Feb 15 '23 15:02

Himanshu Mishra


server{
    location /v1 {
        if ($request_method != 'OPTIONS' ) {
            header_filter_by_lua_block{
                local allowed = {["cache-control"]= true,["content-language"]=true,["content-type"]=true,["expires"]=true};
                for key,value in pairs (ngx.resp.get_headers()) do
                    if (allowed[string.lower(key)]==nil) then
                        ngx.header[key]="";
                    end
                end
            }
        }
    }
    proxy_pass https://smth:8080; 
}

This is my example how to change the headers sent to the client

Note that ngx.header is not a normal Lua table and as such, it is not possible to iterate through it using the Lua ipairs function.

Note: HEADER and VALUE will be truncated if they contain the \r or \n characters. The truncated values will contain all characters up to (and excluding) the first occurrence of \r or \n.

For reading request headers, use the ngx.req.get_headers function instead. (https://github.com/openresty/lua-nginx-module#ngxheaderheader)

like image 34
Doc Dark Avatar answered Feb 15 '23 14:02

Doc Dark