Problems about https Reverse Proxy (nginx) for Nextcloud

Support intro

Sorry to hear you’re facing problems :slightly_frowning_face:

help.nextcloud.com is for home/non-enterprise users. If you’re running a business, paid support can be accessed via portal.nextcloud.com where we can ensure your business keeps running smoothly.

In order to help you as quickly as possible, before clicking Create Topic please provide as much of the below as you can. Feel free to use a pastebin service for logs, otherwise either indent short log examples with four spaces:

example

Or for longer, use three backticks above and below the code snippet:

longer
example
here

Some or all of the below information will be requested if it isn’t supplied; for fastest response please provide as much as you can :heart:

Nextcloud version (eg, 20.0.5): 22.0.0.11
Operating system and version (eg, Ubuntu 20.04): TrueNAS-12.0-U2.1
Apache or nginx version (eg, Apache 2.4.25): nginx/1.20.1
PHP version (eg, 7.4): 7.4.21 (cli) (built: Jul 6 2021 01:55:31) ( NTS )

The issue you are facing: No ‘trusted_domains’ is needed for Nextcloud Access when Nextcloud is behind Reverse Proxy (nginx)

Is this the first time you’ve seen this error? (Y/N): Y

Steps to replicate it:

  1. Add vhost to nginx proxy server
  2. Comment the line related to ‘trusted_domains’
  3. Nextcloud will not show any error screen

Hi, everyone. I am new to Nextcloud. Currently I follow Samuel Dowling’s guide with some adjustment to build a Nextcloud server.
https://www.samueldowling.com/2020/07/24/install-nextcloud-on-freenas-iocage-jail-with-hardened-security/

After the build and some testing, I start to put nextcloud behind my nginx proxy server so that I can access nextcloud in Internet.
However, I find that if I add the below code. Some parameters like ‘trusted_domains’ will not work anymore.
I have tried to comment ‘trusted_domains’, and find that Nextcloud works as normal.
In normal operation, the ‘trusted_domains’ should be a must so that the Nextcloud will only operate in ‘trusted_domains’.

  /*'trusted_domains' =>
  array (
    0 => 'mynextcloud.domain',
  ),*/

  'overwrite.cli.url' => 'https://mynextcloud.domain',
  'overwritehost'     => 'mynextcloud.domain',
  'overwriteprotocol' => 'https',

Also, I would like to know if I need to add these codes. In my testing, tese codes have no effect of Nextcloud.

'proxy' => '',
'trusted_proxies' => [''],

Besides, there are warnings in Security & setup warnings:
Your web server is not properly set up to resolve “/.well-known/webfinger”. Further information can be found in the documentation :arrow_upper_right:.
Your web server is not properly set up to resolve “/.well-known/nodeinfo”. Further information can be found in the documentation :arrow_upper_right:.
Your web server is not properly set up to resolve “/.well-known/caldav”. Further information can be found in the documentation :arrow_upper_right:.
Your web server is not properly set up to resolve “/.well-known/carddav”. Further information can be found in the documentation :arrow_upper_right:.

Without proxy, I receive these two only, do I need to solve the problems immediately?
Your web server is not properly set up to resolve “/.well-known/webfinger”. Further information can be found in the documentation :arrow_upper_right:.
Your web server is not properly set up to resolve “/.well-known/nodeinfo”. Further information can be found in the documentation :arrow_upper_right:.

The output of your Nextcloud log in Admin > Logging:
Should be useless, the Logging seems to be about the “Bug in DnsPinMiddleware.php, unable to resolve hostname #27870

[PHP] Error: Invalid argument supplied for foreach() at /usr/local/www/nextcloud/lib/private/Http/Client/DnsPinMiddleware.php#69

GET /index.phpajax/checksetup

[PHP] Error: count(): Parameter must be an array or an object that implements Countable at /usr/local/www/nextcloud/lib/private/Http/Client/DnsPinMiddleware.php#68

GET /index.phpajax/checksetup

[PHP] Error: dns_get_record(): DNS Query failed at /usr/local/www/nextcloud/lib/private/Http/Client/DnsPinMiddleware.php#66

GET /index.phpajax/checksetup

The output of your config.php file in /path/to/nextcloud (make sure you remove any identifiable information!):

<?php
$CONFIG = array (
  'instanceid' => 'instanceid',
  'passwordsalt' => 'passwordsalt',
  'secret' => 'secret',
  /*'trusted_domains' =>
  array (
    0 => 'mynextcloud.domain',
  ),*/
  'datadirectory' => '/usr/local/www/nextcloud/data',
  'dbtype' => 'mysql',
  'version' => '22.0.0.11',
  //'overwrite.cli.url' => 'https://mynextcloud.lan',
  'dbname' => 'nextcloud',
  'dbhost' => 'localhost:/tmp/mysql.sock',
  'dbport' => '',
  'dbtableprefix' => 'oc_',
  'mysql.utf8mb4' => true,
  'dbuser' => 'ncdbuser',
  'dbpassword' => 'ncdbpassword',
  'installed' => true,
  'redis' =>
  array (
    'host' => '/var/run/redis/redis.sock',
    'port' => 0,
  ),
  'memcache.local' => '\\OC\\Memcache\\APCu',
  'memcache.locking' => '\\OC\\Memcache\\Redis',
  'default_phone_region' => 'HK',
  'loglevel' => 2,
  'enable_previews' => false,
  'overwrite.cli.url' => 'https://mynextcloud.domain',
  'overwritehost'     => 'mynextcloud.domain',
  'overwriteprotocol' => 'https',
  'overwritewebroot'  => '/'
);

The output of your Apache/nginx/system log in /var/log/____:

From /var/log/error.log, all error are below line with different time
2021/07/20 13:58:48 [error] 13247#101924: *7955 FastCGI sent in stderr: "PHP message: PHP Parse error:  syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' in /usr/local/www/nextcloud/config/config.php on line 11" while reading response header from upstream, client: myPC.ip, server: nextcloud.lan, request: "GET /ocs/v2.php/apps/serverinfo/api/v1//basicdata?format=json HTTP/2.0", upstream: "fastcgi://127.0.0.1:9000", host: "nextcloud.lan"

My nginx proxy server vhost file is here

upstream mynextcloud.backend {
    server      mynextcloud.lan:443;
}

server {
    listen      80;
    server_name mynextcloud.domain;

    include     snippets/error_page.conf;

    access_log  /var/log/nginx/80.mynextcloud.domain.access.log;
    error_log   /var/log/nginx/80.mynextcloud.domain.error.log;

    location    / {
        return  301 https://$host$request_uri;
    }
}

server {
    listen      443 ssl http2;
    server_name mynextcloud.domain;

    error_page  497 301 =307 https://$host:$server_port$request_uri;

    include     snippets/domain.cert.conf;
    include     snippets/error_page.conf;
    include     snippets/ssl-hsts.conf;
    #include     snippets/ssl-params.conf;
    include     snippets/ssl-params-ocsp.conf;
    #include     snippets/ssl-params-cert.conf;

    access_log  /var/log/nginx/443.mynextcloud.domain.access.log;
    error_log   /var/log/nginx/443.mynextcloud.domain.error.log;

    fastcgi_request_buffering   off;
    fastcgi_read_timeout        3600s;
    client_max_body_size        16G;
    proxy_max_temp_file_size    16384m;

    location    / {
        proxy_pass  https://mynextcloud.backend;
    }

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

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

My nginx nextcloud vhost file is here

upstream php-handler {
    server 127.0.0.1:9000;
    #server unix:/var/run/php/php7.4-fpm.sock;
}

server {
    listen 80;
    server_name mynextcloud.lan;

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

server {
    listen 443  ssl http2;
    server_name mynextcloud.lan;

    include     snippets/lan.cert.conf;
    include     snippets/error_page.conf;
    include     snippets/ssl-hsts.conf;
    #include     snippets/ssl-params.conf;
    include     snippets/ssl-params-ocsp.conf;
    #include     snippets/ssl-params-cert.conf;

    # Use Mozilla's guidelines for SSL/TLS settings
    # https://mozilla.github.io/server-side-tls/ssl-config-generator/

    # HSTS settings
    # WARNING: Only add the preload option once you read about
    # the consequences in https://hstspreload.org/. This option
    # will add the domain to a hardcoded list that is shipped
    # in all major browsers and getting removed from this list
    # could take several months.
    #add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;" always;

    # set max upload size
    #client_max_body_size 512M;
    client_max_body_size 16G;
    fastcgi_buffers 64 4K;

    fastcgi_read_timeout 3600; # For Large File Transfer

    # 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;

    # Pagespeed is not supported by Nextcloud, so if your server is built
    # with the `ngx_pagespeed` module, uncomment this line to disable it.
    #pagespeed off;

    # HTTP response headers borrowed from Nextcloud `.htaccess`
    add_header Referrer-Policy                      "no-referrer"   always;
    add_header X-Content-Type-Options               "nosniff"       always;
    add_header X-Download-Options                   "noopen"        always;
    add_header X-Frame-Options                      "SAMEORIGIN"    always;
    add_header X-Permitted-Cross-Domain-Policies    "none"          always;
    add_header X-Robots-Tag                         "none"          always;
    add_header X-XSS-Protection                     "1; mode=block" always;

    # Remove X-Powered-By, which is an information leak
    fastcgi_hide_header X-Powered-By;

    # Path to the root of your installation
    #root /var/www/nextcloud;
    root /usr/local/www/nextcloud/;

    # Specify how to handle directories -- specifying `/index.php$request_uri`
    # here as the fallback means that Nginx always exhibits the desired behaviour
    # when a client requests a path that corresponds to a directory that exists
    # on the server. In particular, if that directory contains an index.php file,
    # that file is correctly served; if it doesn't, then the request is passed to
    # the front-end controller. This consistent behaviour means that we don't need
    # to specify custom rules for certain paths (e.g. images and other assets,
    # `/updater`, `/ocm-provider`, `/ocs-provider`), and thus
    # `try_files $uri $uri/ /index.php$request_uri`
    # always provides the desired behaviour.
    index index.php index.html /index.php$request_uri;

    # Rule borrowed from `.htaccess` to handle Microsoft DAV clients
    location = / {
        if ( $http_user_agent ~ ^DavClnt ) {
            return 302 /remote.php/webdav/$is_args$args;
        }
    }

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

    # Make a regex exception for `/.well-known` so that clients can still
    # access it despite the existence of the regex rule
    # `location ~ /(\.|autotest|...)` which would otherwise handle requests
    # for `/.well-known`.
    location ^~ /.well-known {
        # The rules in this block are an adaptation of the rules
        # in `.htaccess` that concern `/.well-known`.

        location = /.well-known/carddav { return 301 /remote.php/dav/; }
        location = /.well-known/caldav  { return 301 /remote.php/dav/; }

        location /.well-known/acme-challenge    { try_files $uri $uri/ =404; }
        location /.well-known/pki-validation    { try_files $uri $uri/ =404; }

        # Let Nextcloud's API for `/.well-known` URIs handle all other
        # requests by passing them to the front-end controller.
        return 301 /index.php$request_uri;
    }

    # Rules borrowed from `.htaccess` to hide certain paths from clients
    location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/)  { return 404; }
    location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console)                { return 404; }

    # Ensure this block, which passes PHP files to the PHP process, is above the blocks
    # which handle static assets (as seen below). If this block is not declared first,
    # then Nginx will encounter an infinite rewriting loop when it prepends `/index.php`
    # to the URI, resulting in a HTTP 500 error response.
    location ~ \.php(?:$|/) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        set $path_info $fastcgi_path_info;

        try_files $fastcgi_script_name =404;

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $path_info;
        fastcgi_param HTTPS on;

        fastcgi_param modHeadersAvailable true;         # Avoid sending the security headers twice
        fastcgi_param front_controller_active true;     # Enable pretty urls
        fastcgi_pass php-handler;

        fastcgi_intercept_errors on;
        fastcgi_request_buffering off;
    }

    location ~ \.(?:css|js|svg|gif|png|jpg|ico)$ {
        try_files $uri /index.php$request_uri;
        expires 6M;         # Cache-Control policy borrowed from `.htaccess`
        access_log off;     # Optional: Don't log access to assets
    }

    location ~ \.woff2?$ {
        try_files $uri /index.php$request_uri;
        expires 7d;         # Cache-Control policy borrowed from `.htaccess`
        access_log off;     # Optional: Don't log access to assets
    }

    # Rule borrowed from `.htaccess`
    location /remote {
        return 301 /remote.php$request_uri;
    }

    location / {
        try_files $uri $uri/ /index.php$request_uri;
    }
}