Search code examples
luahaproxydistributed-systemsystem-designx-forwarded-for

Lua sample-fetch 'routeIP': runtime error: /etc/haproxy/route_req.lua:3: attempt to call a nil value (method 'fhdr') from /etc/haproxy/route_req.lua


I was trying to print my 'X-forwarded-for' header using LUA script in HAProxy. But I am getting error

/var/log/haproxy.log

May 18 18:37:06 ubuntu-s-1vcpu-1gb-blr1-01 haproxy[161927]: [ALERT] 137/183706 (161927) : Lua sample-fetch 'routeIP': runtime error: /etc/haproxy/route_req.lua:3: attempt to call a nil value (method 'fhdr') from /etc/haproxy/route_req.lua:3 C function line 1.
May 18 18:37:07 ubuntu-s-1vcpu-1gb-blr1-01 haproxy[161927]: [ALERT] 137/183707 (161927) : Lua sample-fetch 'routeIP': runtime error: /etc/haproxy/route_req.lua:3: attempt to call a nil value (method 'fhdr') from /etc/haproxy/route_req.lua:3 C function line 1.
 Lua sample-fetch 'routeIP': runtime error: /etc/haproxy/route_req.lua:3: attempt to call a nil value (method 'fhdr') from /etc/haproxy/route_req.lua:3 C function line 1.

Here is my haproxy.cfg file, where I am setting the X-forwarded-for header.

#HAProxy for web servers
frontend web-frontend
  bind 10.122.0.2:80
  bind 139.59.75.106:80
  mode http

  http-request set-header X-Forwarded-Proto https if { ssl_fc } # For Proto
  http-request add-header X-Real-Ip %[src] # Custom header with src IP
  option forwardfor # X-forwarded-for

  use_backend %[lua.routeIP]

The Lua script where I am printing the same route_req.lua

local function getIP(txn)
        local clientip = txn.f:src()
        local src = txn.f:fhdr("x-forwarded-for");

        core.log(core.info, "ClientP and XForwardedFor header : " .. clientip .. " - " .. src)
        // My code goes here

end

core.register_fetches('routeIP', getIP)

Where exactly I am going wrong why isn't the X-forwarded-for header set?

As I understand this field contains the IP address of the last device as well which forwarded my request, so I can't use just the src.

Provides a list of connection IP addresses.

The load balancer appends the last remote peer address to the X-Forwarded-For field from the incoming request. A comma and space precede the appended address. If the client request header does not include an X-Forwarded-For field, this value is equal to the X-Real-IP value.


Solution

  • That error means that txn.f doesn't contain a method called fhdr. Maybe you meant req_fhdr instead.