Nginx Lua设置代理头

4

我相信这应该是一个简单的问题,但是我却找不到答案。我正在尝试设置代理头,我已经尝试了以下几种方法:

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

或者

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

如何正确设置代理头。

谢谢, stabiuti

3个回答

7

为了设置或清除发送到proxy_pass的头文件,您可以使用以下方法:

要设置标题,请使用:

ngx.req.set_header(header_name, value)

清除标题,使用:
ngx.req.clear_header(header)

清除所有标头,您可以编写:
for header, _ in pairs(ngx.req.get_headers()) do
    ngx.req.clear_header(header)
end

现在来回答你的问题,你可以使用

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

请确保将其编写在access_by_lua或rewrite_by_lua中。

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; 
}

以下是如何更改发送到客户端的标头示例:

请注意,ngx.header不是普通的Lua表,因此无法使用Lua ipairs函数迭代访问。

注意:如果HEADER或VALUE包含\r或\n字符,则将被截断。截断后的值将包含所有字符,直到第一个\r或\n的出现位置(不包括该字符)。

要读取请求标头,请改用ngx.req.get_headers函数。 (https://github.com/openresty/lua-nginx-module#ngxheaderheader)


0

这不是正确的方法。您不需要使用lua来设置代理头。没有lua,您可以简单地执行以下操作:

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

您可以在此处阅读有关nginx代理模块的更多信息: http://nginx.org/en/docs/http/ngx_http_proxy_module.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接