b0g3r: I found a discussion about this feature: https://github.com/encode/uvicorn/commit/723d3dc225cc2658634bdbfa29570ceedd6d40ed#r36079732

So, I'll try to find examples from other servers with this feature and make comparison
iamlordaubrey: > From my understanding, the idea here is to return the actual client ip address. This as it is returns the last ip address (which could be a proxy address)

Ok, I think I get it now
rlittlefield: This change is working well for me. The old way of specifying N proxies worked better for my use case because google cloud load balancers + kubernetes services always adds two hosts to the header, and I don't get to know what those are in advance. I can get this to work with your changes. Thank you!
iamlordaubrey: @tomchristie please can someone take a look at this PR? Sorry for the inconvenience 🙏 
HereComesTheRainAgain: Is there any chance to release this any time soon? 
Slow API (https://pypi.org/project/slowapi/) can not work without this change.
dp-rufus: @euri10 I'm not sure a fall-through case is necessary above - `None` might be the most sensible return value under the (unlikely) circumstances that would trigger this behaviour.

@tomchristie could you take another look at this PR please? I've just been bitten by this problem in the wild and it would be good to get this merged. Thanks
euri10: updated it in https://github.com/encode/uvicorn/compare/master...euri10:b0g3r-uvicorn-590?expand=1 to solve conflicts because of the "new" test suite (original PR was done previous to the test suite being "revamped")
b0g3r: @euri10 Thank you for your comment!

I rebased this PR onto master and fix related issues (`127.0.0.1` instead of `testclient` and others.) The last piece to merge is code review, right?

diff --git a/uvicorn/middleware/proxy_headers.py b/uvicorn/middleware/proxy_headers.py
index 05f4f70..23901bd 100644
--- a/uvicorn/middleware/proxy_headers.py
+++ b/uvicorn/middleware/proxy_headers.py
@@ -8,17 +8,28 @@ the connecting client, rather that the connecting proxy.
 
 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#Proxies
 """
+from typing import List
 
 
 class ProxyHeadersMiddleware:
     def __init__(self, app, trusted_hosts="127.0.0.1"):
         self.app = app
         if isinstance(trusted_hosts, str):
-            self.trusted_hosts = [item.strip() for item in trusted_hosts.split(",")]
+            self.trusted_hosts = {item.strip() for item in trusted_hosts.split(",")}
         else:
-            self.trusted_hosts = trusted_hosts
+            self.trusted_hosts = set(trusted_hosts)
         self.always_trust = "*" in self.trusted_hosts
 
+    def get_trusted_client_host(
+        self, x_forwarded_for_hosts
+    ):  # type: (List[str]) -> str
+        if self.always_trust:
+            return x_forwarded_for_hosts[0]
+
+        for host in reversed(x_forwarded_for_hosts):
+            if host not in self.trusted_hosts:
+                return host
+
     async def __call__(self, scope, receive, send):
         if scope["type"] in ("http", "websocket"):
             client_addr = scope.get("client")
@@ -38,7 +49,10 @@ class ProxyHeadersMiddleware:
                     # X-Forwarded-For header. We've lost the connecting client's port
                     # information by now, so only include the host.
                     x_forwarded_for = headers[b"x-forwarded-for"].decode("latin1")
-                    host = x_forwarded_for.split(",")[-1].strip()
+                    x_forwarded_for_hosts = [
+                        item.strip() for item in x_forwarded_for.split(",")
+                    ]
+                    host = self.get_trusted_client_host(x_forwarded_for_hosts)
                     port = 0
                     scope["client"] = (host, port)
 

Proxy Middleware grabs the last IP in `x-forwarded-for`, not the first
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For says the first IP in is a client IP, but ProxyHeadersMiddleware grabs the last IP:
https://github.com/encode/uvicorn/blob/9d9f8820a8155e36dcb5e4d4023f470e51aa4e03/uvicorn/middleware/proxy_headers.py#L41
diff --git a/tests/middleware/test_proxy_headers.py b/tests/middleware/test_proxy_headers.py
index d20adcd..aacf789 100644
--- a/tests/middleware/test_proxy_headers.py
+++ b/tests/middleware/test_proxy_headers.py
@@ -13,34 +13,79 @@ async def app(scope, receive, send):
     await response(scope, receive, send)
 
 
-app = ProxyHeadersMiddleware(app, trusted_hosts="*")
-
-
 @pytest.mark.asyncio
-async def test_proxy_headers():
-    async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:
+@pytest.mark.parametrize(
+    ("trusted_hosts", "response_text"),
+    [
+        # always trust
+        ("*", "Remote: https://1.2.3.4:0"),
+        # trusted proxy
+        ("127.0.0.1", "Remote: https://1.2.3.4:0"),
+        (["127.0.0.1"], "Remote: https://1.2.3.4:0"),
+        # trusted proxy list
+        (["127.0.0.1", "10.0.0.1"], "Remote: https://1.2.3.4:0"),
+        ("127.0.0.1, 10.0.0.1", "Remote: https://1.2.3.4:0"),
+        # request from untrusted proxy
+        ("192.168.0.1", "Remote: http://127.0.0.1:123"),
+    ],
+)
+async def test_proxy_headers_trusted_hosts(trusted_hosts, response_text):
+    app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts)
+    async with httpx.AsyncClient(
+        app=app_with_middleware, base_url="http://testserver"
+    ) as client:
         headers = {"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"}
         response = await client.get("/", headers=headers)
+
     assert response.status_code == 200
-    assert response.text == "Remote: https://1.2.3.4:0"
+    assert response.text == response_text
 
 
 @pytest.mark.asyncio
-async def test_proxy_headers_no_port():
-    async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:
-        headers = {"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"}
+@pytest.mark.parametrize(
+    ("trusted_hosts", "response_text"),
+    [
+        # always trust
+        ("*", "Remote: https://1.2.3.4:0"),
+        # all proxies are trusted
+        (
+            ["127.0.0.1", "10.0.2.1", "192.168.0.2"],
+            "Remote: https://1.2.3.4:0",
+        ),
+        # order doesn't matter
+        (
+            ["10.0.2.1", "192.168.0.2", "127.0.0.1"],
+            "Remote: https://1.2.3.4:0",
+        ),
+        # should set first untrusted as remote address
+        (["192.168.0.2", "127.0.0.1"], "Remote: https://10.0.2.1:0"),
+    ],
+)
+async def test_proxy_headers_multiple_proxies(trusted_hosts, response_text):
+    app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts)
+    async with httpx.AsyncClient(
+        app=app_with_middleware, base_url="http://testserver"
+    ) as client:
+        headers = {
+            "X-Forwarded-Proto": "https",
+            "X-Forwarded-For": "1.2.3.4, 10.0.2.1, 192.168.0.2",
+        }
         response = await client.get("/", headers=headers)
+
     assert response.status_code == 200
-    assert response.text == "Remote: https://1.2.3.4:0"
+    assert response.text == response_text
 
 
 @pytest.mark.asyncio
 async def test_proxy_headers_invalid_x_forwarded_for():
-    async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:
+    app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts="*")
+    async with httpx.AsyncClient(
+        app=app_with_middleware, base_url="http://testserver"
+    ) as client:
         headers = httpx.Headers(
             {
                 "X-Forwarded-Proto": "https",
-                "X-Forwarded-For": "\xf0\xfd\xfd\xfd, 1.2.3.4",
+                "X-Forwarded-For": "1.2.3.4, \xf0\xfd\xfd\xfd",
             },
             encoding="latin-1",
         )

pip install -e .[standard]
parse_log_pytest
requirements.txt
pytest coverage
3.9
requirements.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
anyio==3.7.1
autoflake==2.3.1
babel==2.17.0
backports.tarfile==1.2.0
backrefs==5.8
black==25.1.0
certifi==2025.1.31
cffi==1.17.1
charset-normalizer==3.4.1
click==7.1.2
colorama==0.4.6
coverage==7.8.0
cryptography==44.0.2
docutils==0.21.2
exceptiongroup==1.2.2
flake8==7.2.0
ghp-import==2.1.0
h11==0.14.0
httpcore==0.12.3
httptools==0.1.2
httpx==0.16.1
id==1.5.0
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
isort==6.0.1
jaraco.classes==3.4.0
jaraco.context==6.0.1
jaraco.functools==4.1.0
jeepney==0.9.0
Jinja2==3.1.6
keyring==25.6.0
Markdown==3.7
markdown-it-py==3.0.0
MarkupSafe==3.0.2
mccabe==0.7.0
mdurl==0.1.2
mergedeep==1.3.4
mkdocs==1.6.1
mkdocs-get-deps==0.2.0
mkdocs-material==9.6.10
mkdocs-material-extensions==1.3.1
more-itertools==10.6.0
mypy==1.15.0
mypy-extensions==1.0.0
nh3==0.2.21
packaging==24.2
paginate==0.5.7
pathspec==0.12.1
platformdirs==4.3.7
pluggy==1.5.0
pycodestyle==2.13.0
pycparser==2.22
pyflakes==3.3.2
Pygments==2.19.1
pymdown-extensions==10.14.3
pytest==8.3.5
pytest-asyncio==0.14.0
pytest-mock==3.14.0
python-dateutil==2.9.0.post0
python-dotenv==1.1.0
PyYAML==6.0.2
pyyaml_env_tag==0.1
readme_renderer==44.0
requests==2.32.3
requests-toolbelt==1.0.0
rfc3986==1.5.0
rich==14.0.0
SecretStorage==3.3.3
six==1.17.0
sniffio==1.3.1
tomli==2.2.1
trustme==1.2.1
twine==6.1.0
typing_extensions==4.13.0
urllib3==2.3.0
-e git+https://github.com/encode/uvicorn.git@baff0843389a65dcd9b94f667f95a4b70d28e12f#egg=uvicorn
uvloop==0.21.0
watchdog==6.0.0
watchgod==0.8.2
websockets==8.1
wsproto==1.0.0
zipp==3.21.0

name: uvicorn
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.4.4=h6a678d5_1
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=3.0.16=h5eee18b_0
  - pip=25.0=py39h06a4308_0
  - python=3.9.21=he870216_1
  - readline=8.2=h5eee18b_0
  - setuptools=75.8.0=py39h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - tzdata=2025a=h04d1e81_0
  - wheel=0.45.1=py39h06a4308_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - anyio==3.7.1
      - autoflake==2.3.1
      - babel==2.17.0
      - backports-tarfile==1.2.0
      - backrefs==5.8
      - black==25.1.0
      - certifi==2025.1.31
      - cffi==1.17.1
      - charset-normalizer==3.4.1
      - click==7.1.2
      - colorama==0.4.6
      - coverage==7.8.0
      - cryptography==44.0.2
      - docutils==0.21.2
      - exceptiongroup==1.2.2
      - flake8==7.2.0
      - ghp-import==2.1.0
      - h11==0.14.0
      - httpcore==0.12.3
      - httptools==0.1.2
      - httpx==0.16.1
      - id==1.5.0
      - idna==3.10
      - importlib-metadata==8.6.1
      - iniconfig==2.1.0
      - isort==6.0.1
      - jaraco-classes==3.4.0
      - jaraco-context==6.0.1
      - jaraco-functools==4.1.0
      - jeepney==0.9.0
      - jinja2==3.1.6
      - keyring==25.6.0
      - markdown==3.7
      - markdown-it-py==3.0.0
      - markupsafe==3.0.2
      - mccabe==0.7.0
      - mdurl==0.1.2
      - mergedeep==1.3.4
      - mkdocs==1.6.1
      - mkdocs-get-deps==0.2.0
      - mkdocs-material==9.6.10
      - mkdocs-material-extensions==1.3.1
      - more-itertools==10.6.0
      - mypy==1.15.0
      - mypy-extensions==1.0.0
      - nh3==0.2.21
      - packaging==24.2
      - paginate==0.5.7
      - pathspec==0.12.1
      - platformdirs==4.3.7
      - pluggy==1.5.0
      - pycodestyle==2.13.0
      - pycparser==2.22
      - pyflakes==3.3.2
      - pygments==2.19.1
      - pymdown-extensions==10.14.3
      - pytest==8.3.5
      - pytest-asyncio==0.14.0
      - pytest-mock==3.14.0
      - python-dateutil==2.9.0.post0
      - python-dotenv==1.1.0
      - pyyaml==6.0.2
      - pyyaml-env-tag==0.1
      - readme-renderer==44.0
      - requests==2.32.3
      - requests-toolbelt==1.0.0
      - rfc3986==1.5.0
      - rich==14.0.0
      - secretstorage==3.3.3
      - six==1.17.0
      - sniffio==1.3.1
      - tomli==2.2.1
      - trustme==1.2.1
      - twine==6.1.0
      - typing-extensions==4.13.0
      - urllib3==2.3.0
      - uvloop==0.21.0
      - watchdog==6.0.0
      - watchgod==0.8.2
      - websockets==8.1
      - wsproto==1.0.0
      - zipp==3.21.0
prefix: /opt/conda/envs/uvicorn

tests/middleware/test_proxy_headers.py::test_proxy_headers_multiple_proxies[*-Remote: tests/middleware/test_proxy_headers.py::test_proxy_headers_multiple_proxies[trusted_hosts1-Remote: tests/middleware/test_proxy_headers.py::test_proxy_headers_multiple_proxies[trusted_hosts2-Remote: tests/middleware/test_proxy_headers.py::test_proxy_headers_multiple_proxies[trusted_hosts3-Remote: tests/middleware/test_proxy_headers.py::test_proxy_headers_invalid_x_forwarded_for
tests/middleware/test_proxy_headers.py::test_proxy_headers_trusted_hosts[*-Remote: tests/middleware/test_proxy_headers.py::test_proxy_headers_trusted_hosts[127.0.0.1-Remote: tests/middleware/test_proxy_headers.py::test_proxy_headers_trusted_hosts[trusted_hosts2-Remote: tests/middleware/test_proxy_headers.py::test_proxy_headers_trusted_hosts[trusted_hosts3-Remote: tests/middleware/test_proxy_headers.py::test_proxy_headers_trusted_hosts[127.0.0.1, tests/middleware/test_proxy_headers.py::test_proxy_headers_trusted_hosts[192.168.0.1-Remote:
uvicorn/middleware/proxy_headers.py
uvicorn/middleware/proxy_headers.py