Confused in CsrfViewMiddleware - _origin_verified is checking ports

django version 4.2

Hey I am deploying django at localhost:8000, with nginx in front at localhost:8001.
Also, nginx is behind NAT, let’s say, Internet ↔ 172.0.0.2:6000 ↔ localhost:8001

So in browser requests, Host header should be 172.0.0.2:6000; and Origin header should be http://172.0.0.2:6000.

I’ve added 172.0.0.2 to ALLOWED_HOSTS, so I can GET my web pages. But my POST requests are rejected with this exception:
http://172.0.0.2:6000 does not match any trusted origins.

So I check out the docs Settings | Django documentation | Django.
My understanding is that if origin matches host, no CSRF_TRUSTED_ORIGINS needed to be set. Empty is fine.

But in my case a port number is at the end of the string. When the code compares good_origin with request_origin, missing port number cracks this.

I don’t think this is expected, because if port is 80 then nothing is happening.


Debug info, request origin is scheme://xxx:60522, good_origin is scheme://xxx

wait something went wrong. _origin_verified is correct… It seems to be my browser request causing the problem

I figure it out. It’s a nginx misconfiguration. I forgot to forward port number in host header.

proxy_set_header Host $http_host would forward entire host header to django, as is.