Setting up NC behind a portmapper: Problem with host adress

short version:
How do I configure nextcloud / nginx for accessing it via different URLs while nextcloud is keeping this URLs with custom ports?

Long story:
My Nextcloud is running on a Raspberry Pi and is connected to the router via ethernet. My ISP is delivering me DS-Lite access (only IPv6 public adress, no IPv4). So connecting to the Nextcloud from outside is only via IPv6 possible. For connecting via IPv4 I use a port mapper. So connecting is possible with two different URLs:

  • direct, only IPv6: my-direct-url .net/nextcloud/
  • port mapper: port-mapper-service .net:12345/nextcloud/
failed attempt 1

Idea: using overwritehost in config.php with port mapper adress

'overwritehost' => 'port-mapper-service.net:12345',

Problem: Access via my-direct-url.net isn’t possible anymore, because nextcloud is always redirecting to port-mapper-service:net:12345/nextcloud/

failed attempt 2

Idea:

'overwritehost' => $_SERVER['HTTP_HOST'],

Problem: Access via my-direct-url.net works, but while using port-mapper-service.net:12345/nextcloud/ NC is redirecting to port-mapper-service.net/nextcloud/, port is missing

failed attempt 3

Idea:

'overwritehost' => $_SERVER['SERVER_NAME'],

Problem: Redirecting to 127.0.0.1/nextcloud

failed attempt 4

Idea: writing some lines with if in config.php for making decisions for overwritehost based on $_SERVER[‘HTTP_HOST’]
Problem: Nextcloud isn’t working when adding extra lines to config.php besides $CONFIG = array (…);

Maybe there is an option in nginx, which I’m missing or using not correctly, that is passing the correct information (hostname incl. port) to the nextcloud virtual host, so the nextcloud virtual host can pass the information to nextcloud. Maybe the key is in the following option of nginx, or a similiar one:

        	proxy_set_header X-Forwarded-Host $host;

But I haven’t found the correct setting yet.

My second main idea is to make somehow a dynamic decision for the overwritehost option in config.php, but it seems like that extra script is not allowed by nextcloud in config.php.

I’m also happy about a whole new approach to my problem.

Thanks for your support!

Nextcloud version: 13.0.2.1
Operating system and version: Raspbian (Deebian Strech)
Apache or nginx version: nginx 1.10.3
PHP version: 7.0.27

config.php:

<?php
$CONFIG = array (
  'trusted_domains' => 
  array (
    0 => 'my-direct-url.net',
    1 => 'port-mapper-service.net:12345',
  ),
  'datadirectory' => '/var/www/nextcloud/data',
  'overwritehost' => 'port-mapper-service.net:12345',
  'dbtype' => 'mysql',
  'version' => '13.0.2.1',
  'dbname' => 'nextcloud_db',
  'dbhost' => 'localhost',
  'dbport' => '',
  'dbtableprefix' => 'oc_',
  'dbuser' => 'nextcloud_db_user',
  'installed' => true,
  'maintenance' => false,
  'updater.release.channel' => 'stable',
);

Nginx gateway server configuration (some unintersting lines deleted):

server {
	listen 80 default_server;
	listen [::]:80;

	root /var/www;
	
	server_name port-mapper-service.net;

	location ^~ /.well-known/acme-challenge {
		proxy_pass http://127.0.0.1:81;
		proxy_redirect off;
	}

	location / {
		# Enforce HTTPS
		return 301 https://$server_name:12345/$request_uri;
	}
}
 
server {
	listen 80;
	listen [::]:80 default_server;

	root /var/www;
	
	server_name my-direct-url.net;

	location ^~ /.well-known/acme-challenge {
		proxy_pass http://127.0.0.1:81;
		proxy_redirect off;
	}

	location / {
		# Enforce HTTPS
		return 301 https://$server_name$request_uri;
	}

}

server {
	listen 443 ssl default_server;
	listen [::]:443 ssl default_server;
	root /var/www;
	ssl on;
 
	location = / {
		try_files $uri $uri/ =404;
	}	
	
	#
	# Nextcloud
	#
	location ^~ /nextcloud {
		# Set max. size of a request (important for uploads to Nextcloud)
		client_max_body_size 10G;
		# Besides the timeout values have to be raised in nginx' Nextcloud config, these values have to be raised for the proxy as well
		proxy_connect_timeout 3600;
		proxy_send_timeout 3600;
		proxy_read_timeout 3600;
		send_timeout 3600;
		proxy_buffering off;
		proxy_request_buffering off;
		proxy_max_temp_file_size 10240;
        	proxy_set_header X-Forwarded-Host $host;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_pass http://127.0.0.1:82;
		proxy_redirect off;
	}	
}

nginx virtual host nextcloud:

upstream php-handler {

    server unix:/run/php/php7.0-fpm.sock;
}

server {
    listen 127.0.0.1:82;
    server_name 127.0.0.1;
 
    # Add headers to serve security related headers
    # Use 'proxy_set_header' (not 'add_header') as the headers have to be passed through a proxy.
    proxy_set_header Strict-Transport-Security "max-age=15768000; includeSubDomains; always;";
    proxy_set_header X-Content-Type-Options "nosniff; always;";
    proxy_set_header X-XSS-Protection "1; mode=block; always;";
    proxy_set_header X-Robots-Tag none;
    proxy_set_header X-Download-Options noopen;
    proxy_set_header X-Permitted-Cross-Domain-Policies none;
 
    # Path to the root of your installation
    root /var/www/;

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location = /.well-known/carddav {
      return 301 $scheme://$host/nextcloud/remote.php/dav;
    }
    location = /.well-known/caldav {
      return 301 $scheme://$host/nextcloud/remote.php/dav;
    }

    location /.well-known/acme-challenge { }

    location ^~ /nextcloud {
 
        # set max upload size
        client_max_body_size 10G;
        fastcgi_buffers 64 4K;

        # Enable gzip but do not remove ETag headers
        gzip on;
        gzip_vary on;
        gzip_comp_level 4;
        gzip_min_length 256;
        gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
        gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

        location /nextcloud/ {
            rewrite ^ /nextcloud/index.php$uri;
        }

        location ~ ^/nextcloud/(?:build|tests|config|lib|3rdparty|templates|data)/ {
            deny all;
        }
        location ~ ^/nextcloud/(?:\.|autotest|occ|issue|indie|db_|console) {
            deny all;
        }



        location ~ ^/nextcloud/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+)\.php(?:$|/) {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;

            #Avoid sending the security headers twice
            fastcgi_param modHeadersAvailable true;
            fastcgi_param front_controller_active true;
            fastcgi_pass php-handler;
            fastcgi_intercept_errors on;
 
            # Raise timeout values.
            # This is especially important when the Nextcloud setup runs into timeouts (504 gateway errors)
		fastcgi_read_timeout 600;
		fastcgi_send_timeout 600;
		fastcgi_connect_timeout 600;
            fastcgi_request_buffering off;
	    
            # Pass PHP variables directly to PHP.
            # This is usually done in the php.ini. For more flexibility, these variables are configured in the nginx config.
		# All the PHP parameters have to be set in one fastcgi_param. When using more 'fastcgi_param PHP_VALUE' directives, the last one will override all the others.
            fastcgi_param PHP_VALUE "open_basedir=/var/www:/tmp/:/var/nextcloud_data:/dev/urandom:/proc/meminfo
		upload_max_filesize = 10G
		post_max_size = 10G
		max_execution_time = 3600
		output_buffering = off";
            
            # Make sure that the real IP of the remote host is passed to PHP.
            fastcgi_param REMOTE_ADDR $http_x_real_ip;
        }

        location ~ ^/nextcloud/(?:updater|ocs-provider)(?:$|/) {
            try_files $uri/ =404;
            index index.php;
        }

        # Adding the cache control header for js and css files
        # Make sure it is BELOW the PHP block
        location ~ \.(?:css|js|woff|svg|gif)$ {
            try_files $uri /nextcloud/index.php$uri$is_args$args;
            proxy_set_header Cache-Control "public, max-age=7200";
            # Add headers to serve security related headers  (It is intended
            # to have those duplicated to the ones above)
            # Again use 'proxy_set_header' (not 'add_header') as the headers have to be passed through a proxy.
            # Before enabling Strict-Transport-Security headers please read
            # into this topic first.
            #proxy_set_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
            # includeSubDomains; preload;";
            proxy_set_header X-Content-Type-Options nosniff;
            #proxy_set_header X-Frame-Options "SAMEORIGIN";
            proxy_set_header X-XSS-Protection "1; mode=block";
            proxy_set_header X-Robots-Tag none;
            proxy_set_header X-Download-Options noopen;
            proxy_set_header X-Permitted-Cross-Domain-Policies none;
            # Optional: Don't log access to assets
            access_log off;
        }

        location ~ \.(?:png|html|ttf|ico|jpg|jpeg)$ {
            try_files $uri /nextcloud/index.php$uri$is_args$args;
            # Optional: Don't log access to other assets
            access_log off;
        }
    }
}

I got a solution for this problem! It is basically not a solution but a workaround, so that the port mapper isn’t needed anymore. It can be found in the letsencrypt forum: https://community.letsencrypt.org/t/custom-port-in-domain-name-port-mapper-ds-lite/63155