4

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

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3
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)

Comments

0

This is not a correct way. You dont need to use lua for setting proxy headers. Without lua, you can simply do:

location / {
    proxy_set_header ZZZZ zzzzz;
    proxy_pass http://127.0.0.1:8888;
}

You can read more about nginx proxy module here: http://nginx.org/en/docs/http/ngx_http_proxy_module.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.