Unable to login behind reverse proxy (Invalid referer header) due to incorrect server name

I am using matomo via docker-compose on my VPS.
There are two proxies involved as far as I can tell

1.) OVH SSL Gateway to my nginx reverse proxy
2.) My nginx reverse proxy to matomo, running also as a docker container

Matomo is served in a subpath of my website. Yesterday, I was able to login, but today it stopped working.

Nginx is set up to forward as follows (I followed the reverse proxy guide)

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header Referer $http_referer;
proxy_set_header X-Forwarded-Proto $scheme;
set_real_ip_from OVH/24;
real_ip_header X-Forwarded-For;

location /stats {
proxy_pass …://matomo;
proxy_redirect off;
proxy_set_header X-Forwarded-Uri /stats;
rewrite /stats/(.*) /$1 break;
}

Matomo is configured as follows
[General]
proxy_client_headers = “HTTP_X_FORWARDED_FOR”
proxy_host_headers = “HTTP_X_FORWARDED_HOST”
trusted_hosts = “XXX”
trusted_hosts = “matomo”
proxy_uri_header = 1
assume_secure_protocol = 1
force_ssl = 1

This is what the logs on my side say:
weather-station-matomo-1 | 172.31.0.7 - - [19/Apr/2024:07:23:01 +0000] “POST /?module=Login HTTP/1.0” 200 47586 “…://XXX.de/stats/?module=Login” "Mozilla/5.0 "
weather-station-proxy-1 | 213.32.4.225 - - [19/Apr/2024:07:23:02 +0000] “POST /stats/?module=Login HTTP/1.1” 200 46930 “…://XXX.de/stats/?module=Login” “Mozilla/5.0”
weather-station-matomo-1 | 172.31.0.7 - - [19/Apr/2024:07:23:05 +0000] “POST /?module=Login HTTP/1.0” 403 164199 “…://XXX.de/stats/?module=Login” “Mozilla/5.0”
weather-station-proxy-1 | 213.32.4.232 - - [19/Apr/2024:07:23:05 +0000] “POST /stats/?module=Login HTTP/1.1” 403 56629 “…://XXX.de/stats/?module=Login” “Mozilla/5.0”
This to me seems to indicate that indeed the referer is set correctly?

Looking at the source code, this check seems to be the cause:

EDIT: Even if I monkey patch the checks to succeed on my public origin, I am then forwarded to …://matomo/subdirectory, i.e. the server name is incorrect and refers to the container name, not my public domain

This refers also in these matomo logs
weather-station-matomo-1 | AH00558: apache2: Could not reliably determine the server’s fully qualified domain name, using 172.31.0.5. Set the ‘ServerName’ directive globally to suppress this message
weather-station-matomo-1 | AH00558: apache2: Could not reliably determine the server’s fully qualified domain name, using 172.31.0.5. Set the ‘ServerName’ directive globally to suppress this message

So, I think I fixed the issue. I made sure to set host_validation_use_server_name = 0 (so HTTP_HOST is used), and then added the snippet AFTER the proxy_pass to nginx proxy_set_header Host $host;, as per default proxy_pass WILL update the host header.