Nextcloud behind Nginx reverse proxy returns 502 when
proxy_set_header Host
is set
Hi everyone,
I’m running a Nextcloud instance behind an Nginx reverse proxy and encountering a strange issue. When I add proxy_set_header Host $host;
to the Nginx config, the proxy starts returning a 502 Bad Gateway error.
I’m hoping someone can help me understand what’s going wrong here.
Deployment Setup:
- Frontend (proxy): Nginx on host machine
- Backend: Nextcloud inside Docker, using the official
docker-compose
example - Web server inside container: Apache
- Nextcloud version: 31.0.5.1
- Access domain:
nextcloud.naerdada.com:8888
- Backend address:
http://192.168.0.11:42793
Docker Compose (based on official Nextcloud example):
services:
db:
image: mariadb:lts
restart: always
command: --transaction-isolation=READ-COMMITTED
volumes:
- db:/var/lib/mysql
environment:
- MYSQL_ROOT_PASSWORD=
- MYSQL_PASSWORD=
- MYSQL_DATABASE=nextcloud
- MYSQL_USER=nextcloud
redis:
image: redis:alpine
restart: always
app:
image: nextcloud
restart: always
ports:
- 42793:80
depends_on:
- redis
- db
volumes:
- nextcloud:/var/www/html
environment:
- MYSQL_PASSWORD=
- MYSQL_DATABASE=nextcloud
- MYSQL_USER=nextcloud
- MYSQL_HOST=db
volumes:
nextcloud:
db:
Nginx config (reverse proxy):
listen 8888 ssl;
listen [::]:8888 ssl;
http2 on;
server_name www.naerdada.xyz nextcloud.naerdada.xyz;
location / {
proxy_pass http://192.168.0.11:42793/;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-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-Proto $scheme;
}
The issue occurs only when this line is enabled:
proxy_set_header Host $host;
Behavior:
- Accessing backend directly:
http://192.168.0.11:42793
works perfectly. - Simulated request with curl:
curl -v -H "Host: nextcloud.naerdada.xyz:8888" http://192.168.0.11:42793/index.php
Returns:
HTTP/1.1 302 Found
Location: http://nextcloud.naerdada.xyz:8888/login
- Nginx error log:
upstream prematurely closed connection while reading response header from upstream
Nextcloud config.php
:
'trusted_domains' => [
'nextcloud.naerdada.xyz',
'nextcloud.naerdadatxyz:8888',
'*'
],
'overwritehost' => 'nextcloud.naerdada.xyz:8888',
'overwrite.cli.url' => 'https://nextcloud.naerdada.xyz:8888',
Apache .htaccess
(auto-generated):
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
...
What I’ve tried:
- Removing
proxy_set_header Host
→ no 502 - curl request with
Host:
header works fine - Increasing
proxy_buffers
has no effect - No fatal errors in Nextcloud logs — only minor app warnings
Questions:
- Why does setting
proxy_set_header Host $host;
trigger a 502 error? - Is Apache rejecting the request due to missing
ServerName
or mismatch?
Any help or insights would be very much appreciated. Thanks in advance!