New Install - Bad Gateway 502 / Too many Redirects / Forbidden 403

So I want to preface this with I’m a complete newbie when it comes to nginx and nextcloud. So if there is a config / log file I haven’t posted that would have been useful then please let me know (and if you can tell me where i can find it as I probably dont know).
Also apologies for the long post but I wanted to show what I’ve tried.

I’ve been using the instructions here - https://www.howtoforge.com/tutorial/ubuntu-nginx-nextcloud/

So I’ve spent a few days trying to get nextcloud up and working. The way my servers should be set up is

  1. ISP Router forwarding all traffic to PFsense router (ISP router will be replaced by a pure modem as soon as I can)
  2. pfsense forwards port 80 and port 443 to my webserver
  3. Nginx is running on the webserver although currently just forwards requests to other servers. nextcloud.mydomain .co.uk is forwarded to my services server.
  4. Services server should read the nextcloud.mydomain .co.uk and send it to the local nextcloud location.
    N.B. I have webmin running on both the services and web servers to make my life a little easier.

Router IP: 192.168.2.1
WebServer IP: 192.168.2.88
Services IP: 192.168.2.86

However I change the nginx config on the servers however I seem to either get bad gateway, too many redirects or just the nginx default site.

Current Config

Webserver Nginx (aka Config A version1)

server {
    listen 80;
	server_name nextcloud.mydomain.com;

	return 301 https://$server_name$request_uri;
}

server {
	listen 443 ssl;
	server_name nextcloud.mydomain.com;

	access_log /var/log/nginx/nextcloud.mydomain.com.access.log;
	error_log /var/log/nginx/nextcloud.mydomain.com.error.log;

	client_max_body_size 0;
	underscores_in_headers on;


	location / {
		proxy_headers_hash_max_size 512;
		proxy_headers_hash_bucket_size 64;
		proxy_set_header Host $host;
		proxy_set_header X-Forwarded-Proto $scheme;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

		add_header Front-End-Https on;
		# whatever the IP of your cloud server is on
		proxy_pass http://192.168.2.86;
	}
}

Services Nginx (aka Config B version1

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

server {
    server_name nextcloud.mydomain.com;
    # enforce https
    return 301 https://$server_name$request_uri;

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/nextcloud.mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/nextcloud.mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

server {
    listen 443;

    server_name nextcloud.mydomain.com;

    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this
    # topic first.
    # add_header Strict-Transport-Security "max-age=15552000;
    # includeSubDomains; preload;";
    #
    # 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 X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;

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

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

    # The following 2 rules are only needed for the user_webfinger app.
    # Uncomment it if you're planning to use this app.
    #rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
    #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json
    # last;

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

    # set max upload size
    client_max_body_size 512M;
    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;

    # Uncomment if your server is built with the ngx_pagespeed module
    # This module is currently not supported.
    #pagespeed off;

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

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

    location ~ ^/(?: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;
        fastcgi_param HTTPS on;
        #Avoid sending the security headers twice
        fastcgi_param modHeadersAvailable true;
        fastcgi_param front_controller_active true;
        fastcgi_pass php-handler;
        fastcgi_intercept_errors on;
        fastcgi_request_buffering off;
    }

    location ~ ^/(?: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 /index.php$uri$is_args$args;
        add_header Cache-Control "public, max-age=15778463";
        # Add headers to serve security related headers (It is intended to
        # have those duplicated to the ones above)
        # Before enabling Strict-Transport-Security headers please read into
        # this topic first.
        # add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
        #
        # 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 X-Content-Type-Options nosniff;
        add_header X-XSS-Protection "1; mode=block";
        add_header X-Robots-Tag none;
        add_header X-Download-Options noopen;
        add_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 /index.php$uri$is_args$args;
        # Optional: Don't log access to other assets
        access_log off;
    }
}


server {
    if ($host = nextcloud.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    listen [::]:80;
    server_name nextcloud.mydomain.com;
    return 404; # managed by Certbot


}

Result

# This page isn’t working

**nextcloud.mydomain.com**  redirected you too many times.

* [Try clearing your cookies](https://support.google.com/chrome?p=rl_error&hl=en-GB).

ERR_TOO_MANY_REDIRECTS

Take 2

I found this post which seemed to be along the right track

Taking the Nextcloud in a subdir of root config and tweaking it to the below.

Service Nginx (AKA Config B version 2)

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

server {
    listen 80;
    server_name nextcloud.mydomain.com;
    # enforce https
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name nextcloud.mydomain.com;

    ssl_certificate /etc/letsencrypt/live/nextcloud.mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/nextcloud.mydomain.com/privkey.pem; # managed by Certbot

    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this
    # topic first.
    #add_header Strict-Transport-Security "max-age=15768000;
    # includeSubDomains; preload;";
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_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;
    }

    # The following 2 rules are only needed for the user_webfinger app.
    # Uncomment it if you're planning to use this app.
    # rewrite ^/.well-known/host-meta /nextcloud/public.php?service=host-meta
    # last;
    #rewrite ^/.well-known/host-meta.json
    # /nextcloud/public.php?service=host-meta-json last;

    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 512M;
        fastcgi_buffers 64 4K;

        # Disable gzip to avoid the removal of the ETag header
        gzip off;

        # Uncomment if your server is build with the ngx_pagespeed module
        # This module is currently not supported.
        #pagespeed off;

        error_page 403 /nextcloud/core/templates/403.php;
        error_page 404 /nextcloud/core/templates/404.php;

        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/.+|core/templates/40[34])\.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;
            fastcgi_param HTTPS on;
            #Avoid sending the security headers twice
            fastcgi_param modHeadersAvailable true;
            fastcgi_param front_controller_active true;
            fastcgi_pass php-handler;
            fastcgi_intercept_errors on;
            fastcgi_request_buffering off;
        }

        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)$ {
            try_files $uri /nextcloud/index.php$uri$is_args$args;
            add_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)
            # Before enabling Strict-Transport-Security headers please read
            # into this topic first.
            # add_header Strict-Transport-Security "max-age=15768000;
            # includeSubDomains; preload;";
            add_header X-Content-Type-Options nosniff;
            add_header X-Frame-Options "SAMEORIGIN";
            add_header X-XSS-Protection "1; mode=block";
            add_header X-Robots-Tag none;
            add_header X-Download-Options noopen;
            add_header X-Permitted-Cross-Domain-Policies none;
            # Optional: Don't log access to assets
            access_log off;
        }

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

Result

# This page isn’t working

**nextcloud.mydomain.com**  redirected you too many times.

* [Try clearing your cookies](https://support.google.com/chrome?p=rl_error&hl=en-GB).

ERR_TOO_MANY_REDIRECTS

Take 3

I tried the nginx in webroot to make sure it wasn’t that either.

Services Config akak Config B Version 3

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

server {
    listen 80;
    server_name nextcloud.mydomain.com;
    # enforce https
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name nextcloud.mydomain.com;

    ssl_certificate /etc/letsencrypt/live/nextcloud.mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/nextcloud.mydomain.com/privkey.pem; # managed by 

    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this
    # topic first.
    # add_header Strict-Transport-Security "max-age=15768000;
    # includeSubDomains; preload;";
    #
    # 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 X-Content-Type-Options nosniff;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;

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

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

    # The following 2 rules are only needed for the user_webfinger app.
    # Uncomment it if you're planning to use this app.
    #rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
    #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json
    # last;

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

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

    # Disable gzip to avoid the removal of the ETag header
    gzip off;

    # Uncomment if your server is build with the ngx_pagespeed module
    # This module is currently not supported.
    #pagespeed off;

    error_page 403 /core/templates/403.php;
    error_page 404 /core/templates/404.php;

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

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

    location ~ ^/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+|core/templates/40[34])\.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;
        fastcgi_param HTTPS on;
        #Avoid sending the security headers twice
        fastcgi_param modHeadersAvailable true;
        fastcgi_param front_controller_active true;
        fastcgi_pass php-handler;
        fastcgi_intercept_errors on;
        fastcgi_request_buffering off;
    }

    location ~ ^/(?: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)$ {
        try_files $uri /index.php$uri$is_args$args;
        add_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)
        # Before enabling Strict-Transport-Security headers please read into
        # this topic first.
        # add_header Strict-Transport-Security "max-age=15768000;
        #  includeSubDomains; preload;";
        #
        # 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 X-Content-Type-Options nosniff;
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-XSS-Protection "1; mode=block";
        add_header X-Robots-Tag none;
        add_header X-Download-Options noopen;
        add_header X-Permitted-Cross-Domain-Policies none;
        # Optional: Don't log access to assets
        access_log off;
    }

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

Result (is this progress?)
# 502 Bad Gateway

nginx/1.15.5 (Ubuntu)

Take 4

Stripping out the webserver and just sending the traffic from the pfsense router straight to the services box.

Keeping Config B Version 3
Result
# 502 Bad Gateway

nginx/1.15.5 (Ubuntu)

Keeping Config B Version 2
Result (is this progress?)
# 403 Forbidden

nginx/1.15.5 (Ubuntu)

Keeping Config B Version 1
Result
# This page isn’t working

**nextcloud.mydomain.com**  redirected you too many times.

* [Try clearing your cookies](https://support.google.com/chrome?p=rl_error&hl=en-GB).

ERR_TOO_MANY_REDIRECTS

Take 5

Looking at the 502 result, config B Version 3 and skipping the webserver I looked for solutions on the forum.
Looking at Bad Gateway 502 error it suggested I make sure /etc/nginx/nginx.conf has www-data as the user. However mine seems to be set up correctly.

Services nginx.conf Config C Version 1

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

Trying altering listen.owner and listen.group as per luki938’s suggestion got me the same result i.e. Bad Gateway.
listen.owner = www-data
listen.group = www-data

So I reverted them to www-data.


Take 5

Swaping to the 403 error. Taking Config B Version 2 and routing straight to the services router.
I followed the suggestions in Access denied on nginx

Altering /etc/php/7.1/fpm/pool.d/www.conf by uncommenting the line
security.limit_extensions = .php .php3 .php4 .php5 .php7

and changing fpm/php.ini and cli/php.ini to have cgi.fix_pathinfo=1 (previously they were =0) however this still gave me the 403 error.


At this point I’m not really sure what to do next. I’m kinda just changing random config without much clue about which of the three paths is closest to correct.

Any advice on what I can do to narrow down what has gone wrong or to fix my problem?

Finally I want to point out that I do have mattermost installed on my services VM and that seems to be working without any issue.

this will send the request to your “service server” back to your web server.
the “enforce https” should be done on the web server.
and the service server name should be it’s ip address. since you proxy_pass on the webserver to this ip address. or?

Thanks for the response Reiner_Nippes
Should that be as simple as the below updates to the config?

WebServer (Config A Version 1)

server {
    if ($host = nextcloud.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
	server_name nextcloud.mydomain.com;

	return 301 https://$server_name$request_uri;


}

server {
	listen 443 ssl;
	server_name nextcloud.mydomain.com;

	access_log /var/log/nginx/nextcloud.mydomain.com.access.log;
	error_log /var/log/nginx/nextcloud.mydomain.com.error.log;

	client_max_body_size 0;
	underscores_in_headers on;


	location / {
		proxy_headers_hash_max_size 512;
		proxy_headers_hash_bucket_size 64;
		proxy_set_header Host $host;
		proxy_set_header X-Forwarded-Proto $scheme;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

		add_header Front-End-Https on;
		# whatever the IP of your cloud server is on
		proxy_pass http://192.168.2.86;
	}

    ssl_certificate /etc/letsencrypt/live/nextcloud.mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/nextcloud.mydomain.com/privkey.pem; # managed by Certbot
}

Services Server (Config B Version 4)

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

server {
    listen 443;
    server_name 192.168.2.86;

    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this
    # topic first.
    #add_header Strict-Transport-Security "max-age=15768000;
    # includeSubDomains; preload;";
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_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;
    }

    # The following 2 rules are only needed for the user_webfinger app.
    # Uncomment it if you're planning to use this app.
    # rewrite ^/.well-known/host-meta /nextcloud/public.php?service=host-meta
    # last;
    #rewrite ^/.well-known/host-meta.json
    # /nextcloud/public.php?service=host-meta-json last;

    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 512M;
        fastcgi_buffers 64 4K;

        # Disable gzip to avoid the removal of the ETag header
        gzip off;

        # Uncomment if your server is build with the ngx_pagespeed module
        # This module is currently not supported.
        #pagespeed off;

        error_page 403 /nextcloud/core/templates/403.php;
        error_page 404 /nextcloud/core/templates/404.php;

        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/.+|core/templates/40[34])\.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;
            fastcgi_param HTTPS on;
            #Avoid sending the security headers twice
            fastcgi_param modHeadersAvailable true;
            fastcgi_param front_controller_active true;
            fastcgi_pass php-handler;
            fastcgi_intercept_errors on;
            fastcgi_request_buffering off;
        }

        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)$ {
            try_files $uri /nextcloud/index.php$uri$is_args$args;
            add_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)
            # Before enabling Strict-Transport-Security headers please read
            # into this topic first.
            # add_header Strict-Transport-Security "max-age=15768000;
            # includeSubDomains; preload;";
            add_header X-Content-Type-Options nosniff;
            add_header X-Frame-Options "SAMEORIGIN";
            add_header X-XSS-Protection "1; mode=block";
            add_header X-Robots-Tag none;
            add_header X-Download-Options noopen;
            add_header X-Permitted-Cross-Domain-Policies none;
            # Optional: Don't log access to assets
            access_log off;
        }

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

When I do this it redirects me to https://192.168.2.86 and gives me the following error

This site can’t provide a secure connection

192.168.2.86 sent an invalid response.

  • [Try running Windows Network Diagnostics](javascript:diagnoseErrors()).

ERR_SSL_PROTOCOL_ERROR

Assuming there is something that I’m missing :confused:

server b should listen to port 80. or you should proxy pass to https.

Okay so in my webserver config I’ve changed the line

proxy_pass http://192.168.2.86;

to

proxy_pass https://192.168.2.86;

Now it returns.

# This site can’t provide a secure connection

**192.168.2.86**  sent an invalid response.

* [Try running Windows Network Diagnostics](javascript:diagnoseErrors()).

ERR_SSL_PROTOCOL_ERROR

server a: listen 443 ssl;
server b: listen 443; probably talking http on port 443.
and where did you set the ssl certificates of server b?

do you need https on your internal network between a and b?

I used “sudo certbot --nginx” on each server individually to set up the SSL certs. (i.e. I didn’t create the certs on one server and then copy them over to the other)
Sever A (Webserver) already has listen 443 ssl; and server B (services server) has listen 443;

I don’t really need SSL between the web server and the services server. I could try listening to port 80 instead. See if that improves things.

If I change the config of the webserver (A) to

server {
    if ($host = nextcloud.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
	server_name nextcloud.mydomain.com;

	return 301 https://$server_name$request_uri;


}

server {
	listen 443 ssl;
	server_name nextcloud.mydomain.com;

	access_log /var/log/nginx/nextcloud.mydomain.com.access.log;
	error_log /var/log/nginx/nextcloud.mydomain.com.error.log;

	client_max_body_size 0;
	underscores_in_headers on;


	location / {
		proxy_headers_hash_max_size 512;
		proxy_headers_hash_bucket_size 64;
		proxy_set_header Host $host;
		proxy_set_header X-Forwarded-Proto $scheme;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

		add_header Front-End-Https on;
		# whatever the IP of your cloud server is on
		proxy_pass http://192.168.2.86;
	}

    ssl_certificate /etc/letsencrypt/live/nextcloud.mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/nextcloud.mydomain.com/privkey.pem; # managed by Certbot
}

and the config for the services server (B) to the below

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

server {
    listen 80;
    server_name 192.168.2.86;

    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this
    # topic first.
    #add_header Strict-Transport-Security "max-age=15768000;
    # includeSubDomains; preload;";
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_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;
    }

    # The following 2 rules are only needed for the user_webfinger app.
    # Uncomment it if you're planning to use this app.
    # rewrite ^/.well-known/host-meta /nextcloud/public.php?service=host-meta
    # last;
    #rewrite ^/.well-known/host-meta.json
    # /nextcloud/public.php?service=host-meta-json last;

    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 512M;
        fastcgi_buffers 64 4K;

        # Disable gzip to avoid the removal of the ETag header
        gzip off;

        # Uncomment if your server is build with the ngx_pagespeed module
        # This module is currently not supported.
        #pagespeed off;

        error_page 403 /nextcloud/core/templates/403.php;
        error_page 404 /nextcloud/core/templates/404.php;

        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/.+|core/templates/40[34])\.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;
            fastcgi_param HTTPS on;
            #Avoid sending the security headers twice
            fastcgi_param modHeadersAvailable true;
            fastcgi_param front_controller_active true;
            fastcgi_pass php-handler;
            fastcgi_intercept_errors on;
            fastcgi_request_buffering off;
        }

        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)$ {
            try_files $uri /nextcloud/index.php$uri$is_args$args;
            add_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)
            # Before enabling Strict-Transport-Security headers please read
            # into this topic first.
            # add_header Strict-Transport-Security "max-age=15768000;
            # includeSubDomains; preload;";
            add_header X-Content-Type-Options nosniff;
            add_header X-Frame-Options "SAMEORIGIN";
            add_header X-XSS-Protection "1; mode=block";
            add_header X-Robots-Tag none;
            add_header X-Download-Options noopen;
            add_header X-Permitted-Cross-Domain-Policies none;
            # Optional: Don't log access to assets
            access_log off;
        }

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

Then the error moves to

# This site can’t be reached

**192.168.2.86**  refused to connect.

Try:

* Checking the connection
* [Checking the proxy and the firewall](chrome-error://chromewebdata/#buttons)

ERR_CONNECTION_REFUSED

Not sure if that is a step in the right direction or now?
Should I stick with proxy pass to http:// and go from here or revert to proxy pass to https://?

are you able to access http://192.168.2.86/ within your network?

Going straight to http://192.168.2.86/ gives me

# 403 Forbidden

nginx/1.15.5 (Ubuntu)

and, if it helps, going straight to http://192.168.2.86/nextcloud gives me

# 502 Bad Gateway

nginx/1.15.5 (Ubuntu)

well. looks good.
only nextcloud should run.

# 502 Bad Gateway

means you have an error in the nextcloud setup. fpm-php running?

I’m not sure but maybe you should also change

proxy_pass http://192.168.2.86;

to

proxy_pass http://192.168.2.86/nextcloud;

or configure server b to use http://192.168.2.86/ as the nextcloud url.
I asume you don’t want to use:

https://nextcloud.mydomain.com/nextcloud

btw: why to you use two nginx?

It looks to be running.

If I run

sudo /etc/init.d/php7.1-fpm status

I get

â—Ź php7.1-fpm.service - The PHP 7.1 FastCGI Process Manager
   Loaded: loaded (/lib/systemd/system/php7.1-fpm.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2018-11-10 07:49:02 GMT; 1 day 12h ago
     Docs: man:php-fpm7.1(8)
 Main PID: 535 (php-fpm7.1)
   Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec"
    Tasks: 3 (limit: 4915)
   Memory: 32.5M
   CGroup: /system.slice/php7.1-fpm.service
           ├─535 php-fpm: master process (/etc/php/7.1/fpm/php-fpm.conf)
           ├─556 php-fpm: pool www
           └─558 php-fpm: pool www

Nov 10 07:49:02 mydomain.com systemd[1]: Starting The PHP 7.1 FastCGI Process Manager...
Nov 10 07:49:02 mydomain.com systemd[1]: Started The PHP 7.1 FastCGI Process Manager.

Agreed that I want to use https://nextcloud.mydomain.com rather than https://nextcloud.mydomain.com/nextcloud.
Is that an easy change to make or should I run through the nextcloud setup from scratch again?

N.B. I’m using two Nginx servers because i want my services box to have full access to all of my data.
The main webserver section is being used by me and a friend so I wanted to keep the two separate.
Probably more convoluted that it needs to be and something I likely could have done with user permissions but it allows me to adjust system resources for the two areas independently.

you have to change

root /var/www/;

to

root /var/www/nextcloud;

and remove nextcloud from all the location /nextcloud items.
could be tricky.

you may have a look at my ansible-playbooks to reinstall nextcloud. but please use a newly installed vm.

you can add a second virtual webserver to this installation by copying and editing the nextcloud.conf file in /etc/nginx/conf.

the installation you’ll get is based on carsten riegers config.
https://www.c-rieger.de/nextcloud-14-nginx-installation-guide-for-ubuntu-18-04-lts/

Spent a bit more time on it and I’ve shifted the install to get it working in root.
The main issue seems to have been that with the upstream php-handler.

Setting it to the below seems to have fixed it.

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