Read Cf-Connecting-Ip header for real client IP through Cloudflare tunnel

This commit is contained in:
Graham McIntire 2026-04-02 11:49:11 -05:00
parent b6a5e709b7
commit 9485df4b8d
No known key found for this signature in database
GPG key ID: F4ABF488E6029E59

View file

@ -10,19 +10,26 @@ defmodule MicrowavepropWeb.Plugs.RemoteIp do
def init(opts), do: opts
@impl true
# Cloudflare sets Cf-Connecting-Ip with the real client IP.
# Fall back to X-Forwarded-For for non-tunneled requests (dev, direct).
@ip_headers ["cf-connecting-ip", "x-forwarded-for"]
def call(conn, _opts) do
ip =
case Plug.Conn.get_req_header(conn, "x-forwarded-for") do
[forwarded | _] ->
forwarded
|> String.split(",")
|> hd()
|> String.trim()
|> parse_ip()
@ip_headers
|> Enum.find_value(fn header ->
case Plug.Conn.get_req_header(conn, header) do
[value | _] ->
value
|> String.split(",")
|> hd()
|> String.trim()
|> parse_ip()
_ ->
nil
end
_ ->
nil
end
end)
conn =
if ip do