Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run Nextcloud from Subdirectory #401

Closed
studio315b opened this issue Jul 27, 2018 · 42 comments
Closed

Run Nextcloud from Subdirectory #401

studio315b opened this issue Jul 27, 2018 · 42 comments
Labels
cleanup (ignore): subs examples Compose/Dockerfile/etc integration: proxy Integrating with a reverse proxy needs info Additional info needed to triage needs review Needs confirmation this is still happening or relevant question

Comments

@studio315b
Copy link

How do you tell nextcloud that it's in a sub-directory? Currently each service on my machine is in its own docker instance, and I use Traefik to expose them to different sub-directories on my server:

mydomain/service1
mydomain/service2

Current Behaviour

all links are "/index.php/*"

Desired Behavior

all links are "/nextcloud/index.php/*"

@datenfahrt
Copy link

if I understood you correctly - you have to adjust your nextcloud configuration:

'overwritewebroot'

Look this:

https://docs.nextcloud.com/server/13/admin_manual/configuration_server/reverse_proxy_configuration.html#overwrite-parameters

regards

@studio315b
Copy link
Author

This is what I was looking for. Is there a way to set this setting via docker, or do I need to modify my version of the image?

@udl
Copy link

udl commented Aug 6, 2018

Depending on how you run the docker container. If you mount your filesystem in /var/www/html, for example, you don't need to rebuild the container. You can find the config file in the mounted directory.

@lilarcor
Copy link

can you show us some example, I tried everything I could( 'overwritehost' => '', htaccess.RewriteBase' => , etc.), still failed.

@naramski
Copy link

I had a similar problem and I have created a fix for this issue (Pull request : #527) that contains the an ENV variable NEXTCOULD_OVERWRITEWEBROOT to help define "subdirectories".

Hope it helps,

@omontigny
Copy link

Hi,
I am sorry maybe i didn’t get something but in 16.0.3 version , I still have troubles to access to nextcloud with subdirectories as http://myserver/nextcloud/login

anything a do and every variable i use ( like
overwrite.cli.url
'htaccess.RewriteBase' ...)

i get a redirection to http://myserver/login

except if a use the variable
'overwritewebroot' => '/nextcloud’

but in this case i have ERR_TOO_MANY_REDIRECTS error

Is there something i missed ?

Thank you
Best regards

@johnjore
Copy link

Hi all!
I have the same issue. Migrating to using docker and need nextcloud to use the URL /nextcloud as I have multiple web services all using different folders.

I too get the ERR_TOO_MANY_REDIRECTS error

I've also tried fiddling with the
'htaccess.RewriteBase' => '/nextcloud',
setting as well as RewriteBase / in .htaccess no success. (On some occasions all files were deleted when docker container was started)

PR #527 seems to have morphed into something different so not sure what the fix is for this as I can't get this to work either. What am I missing?

John

@wolftobias
Copy link

I've excatly the same issue and looking for a solution.

@johnjore
Copy link

johnjore commented Aug 13, 2019

Solution, for me, was to have all connections go via proxy when using 'overwritewebroot' => '/nextcloud’

If URL is used via web browser (local network) without reverse proxy => ERR_TOO_MANY_REDIRECTS
With proxy (from internet/external), logon screen appears.

Need to do more validation and testing, but looks good so far.
config.php

  'overwritewebroot' => '/nextcloud',
  'trusted_proxies' =>
  array (
    0 => 'IP_of_my_proxy',
  ),
  'forwarded_for_headers' =>
  array (
    0 => 'HTTP_X_FORWARDED_FOR',
  ),

nginx

    location /nextcloud/ {
        proxy_headers_hash_max_size 512;
        proxy_headers_hash_bucket_size 64;
        add_header Front-End-Https on;
        proxy_pass http://server/;
    }

ymmv...


Update: After moving data and re-using previous DB, Android client re-connected and resumed without any reconfiguration when connecting via proxy. Without going through the proxy, it does not work (at all), lots of errors and timeouts.

I would suspect that 'overwritewebroot' not working when connecting directly is a bug, as per a number of posts here, and hopefully it gets fixed at some point.

@wolftobias
Copy link

I tried everything, not working, by the way I use nextcloud docker image

@Energy23
Copy link

Energy23 commented Sep 3, 2019

My configuration is almost the same.
Nextcloud running in a docker container und nginx as webserver / proxy.
The overwritewebroot command didn't work for me either, what is working is the nginx config:

location /nextcloud {
        proxy_pass http://localhost:8080;
        proxy_set_header X-Forwarded-Host $host:$server_port;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

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

Inside the Docker container, I moved the nextcloud files from /var/www/html to /var/www/html/nextcloud
Then I edited the .htaccess file in the /var/www/html/nextloud almost at the bottom line from
RewriteBase / to RewriteBase /nextcloud

Hope that helps, it seems that the command overwritewebroot does not affect the apache config.

The problem with the container restart doesn't affect this config. After a restart there are new files in the /var/www/html folder of a "fresh" nextcloud installation copied.

Here is are some lines of my config.php

<?php
$CONFIG = array (
  'htaccess.RewriteBase' => '/nextcloud/',
  'memcache.local' => '\\OC\\Memcache\\APCu',
  'apps_paths' =>
  array (
    0 =>
    array (
      'path' => '/var/www/html/nextcloud/apps',
      'url' => '/apps',
      'writable' => false,
    ),
    1 =>
    array (
      'path' => '/var/www/html/nextcloud/custom_apps',
      'url' => '/custom_apps',
      'writable' => true,
    ),
  ),
  'instanceid' => '
  'passwordsalt' => '',
  'secret' => '',
  'trusted_domains' =>
  array (
    0 => 'localhost:PORT',
  ),
  'datadirectory' => '/var/www/html/nextcloud/data',
  'dbtype' => 'mysql',
  'version' => '16.0.1.1',
  'overwrite.cli.url' => 'http://localhost:PORT/nextcloud',
  'dbname' => '',
  'dbhost' => '',
  'dbport' => '',
  'dbtableprefix' => 'oc_',
  'mysql.utf8mb4' => true,
  'dbuser' => '',
  'dbpassword' => ,
  'installed' => true,
  'overwritehost' => 'URL',
  'overwriteprotocol' => 'https',
  'trusted_proxies' =>
  array (
    0 => 'https://***.de',
    1 => 'https://***.de',
  ),
  'mail_smtpmode' => 'smtp',
  'mail_smtpsecure' => 'ssl',
...
  'theme' => '',
  'loglevel' => 0,
  'maintenance' => false,
);

@StokeHead
Copy link

StokeHead commented Mar 4, 2020

After almost giving up i did a final test and found the following to be working.
i created nextcloud with the following command:
podman run --name nextcloud-my -p 8080:80 -v <local_mount_point>:/var/www/html:Z -e -d docker.io/library/nextcloud:18.0.1-apache
vi <local_mount_point>/html/.htaccess
add or change "RewriteBase /" to "RewriteBase /your-sub-context"
vi <local_mount_point>/html/config/config.php
add 'overwritewebroot' => '/your-sub-context',
cd <local_mount_point>/html/
ln -s ../html/ your-sub-context

the symlink is important because otherwise somehow the app does not look at the right path. Most likely configurations within the apache would be required, but i didnt want to modify these as i would have to mount those to my host system then. Anyways, hope that this helps for some of you!

@bakcsa83
Copy link

bakcsa83 commented Mar 27, 2020

@StokeHead Many thanks! It seems htaccess.RewriteBase in config.php does not do its job.

@waynedpj
Copy link

@StokeHead @bakcsa83 thanks to you both but as i documented here i still cannot get Nextcloud served as root but from a subdirectory. it indeed looks like htaccess.RewriteBase does not have an effect but the symlink did not work for me in a non-Docker installation. thanks again.

@bakcsa83
Copy link

bakcsa83 commented Apr 2, 2020

I found out later that there is a command that updates the .htaccess file:
sudo -u www-data php occ maintenance:update:htaccess (did not try it though)
@waynedpj I can only confirm that the solution described by @StokeHead worked for me.

However, the self-update feature did not work (in brand new image) so I just went back to lxc.

@waynedpj
Copy link

waynedpj commented Apr 4, 2020

thanks @bakcsa83 however i forgot to mention that i had already tried running the occ maintenance:update:htaccess command as well, still no luck. i had also followed @StokeHead but could not get it working. regardless thanks again.

@DoctorDrunk
Copy link

Same problem as in nextcloud/server#20338.

We need help here, fumbling around inside the container is not the way to go.

@DoctorDrunk
Copy link

careful bump

@nicbou
Copy link

nicbou commented May 5, 2020

careless bump

@m00nwtchr
Copy link

m00nwtchr commented Jul 28, 2020

For anyone who "just wants it to work", i've been able to get it to work with a modified docker image:

FROM nextcloud

RUN apt-get update && apt-get install sudo

RUN echo "sudo -u www-data php occ maintenance:update:htaccess && /usr/local/bin/apache2-foreground">/usr/local/sbin/apache2-foreground && chmod +x /usr/local/sbin/apache2-foreground

CMD ln -srf /var/www/html /var/www/html/nextcloud && /entrypoint.sh apache2-foreground

then just set overwritewebroot and htaccess.RewriteBase to /nextcloud, and http://localhost:<port>/nextcloud should work! (make sure to restart the container)

Now what would be great is a env var to set the RewriteBase property

EDIT: If the above doesn't work, open /var/www/html/.htaccess scroll to line 112, and change RewriteBase to /nextcloud

EDIT2: Or you can just use the linuxserver/nextcloud image, it uses nginx and you can pretty much effortlessly do this (example from their letsencrypt nginx reverse proxy image, linuxserver/letsencrypt, soon to be renamed linuxserver/swag)

# Assuming this container is called "letsencrypt", edit your nextcloud container's config
# located at /config/www/nextcloud/config/config.php and add the following lines before the ");":
#  'trusted_proxies' => ['letsencrypt'],
#  'overwritewebroot' => '/nextcloud',
#  'overwrite.cli.url' => 'https://your-domain.com/nextcloud',
#
# Also don't forget to add your domain name to the trusted domains array. It should look somewhat like this:
#  array (
#    0 => '192.168.0.1:444', # This line may look different on your setup, don't modify it.
#    1 => 'your-domain.com',
#  ),

# Redirects for DAV clients
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 /nextcloud {
    return 301 $scheme://$host/nextcloud/;
}

location ^~ /nextcloud/ {
    include /config/nginx/proxy.conf;
    resolver 127.0.0.11 valid=30s;
    set $upstream_app nextcloud;
    set $upstream_port 443;
    set $upstream_proto https;
    proxy_pass $upstream_proto://$upstream_app:$upstream_port;

    rewrite /nextcloud(.*) $1 break;
    proxy_max_temp_file_size 2048m;

    proxy_set_header Range $http_range;
    proxy_set_header If-Range $http_if_range;
    proxy_set_header Connection $http_connection;
    proxy_redirect off;
    proxy_ssl_session_reuse off;
}

(not gonna attach proxy.conf here, just have a look at their image)

@SteffRhes
Copy link

SteffRhes commented Aug 17, 2020

Thank you guys!

I could get it working with my setup which also involves a traefik container as reverse proxy. Though I had a minor hickup on the way, namely that the web browser login form and the desktop client's authentication form froze but that can be fixed too as described in the following:

These are the steps on how I got it working:

1.)

Pull the image via a docker-compose.yml:

...
  service_nextcloud:
    image: nextcloud:latest
    volumes:
      - ./volumes/nc_image/html:/var/www/html
...

2.)

Start the containers, then in the nextcloud container the dircetory /var/www/html gets pouplated with code. Within the container I then did:

ln -s /var/www/html/ /var/www/html/intern
chown www-data:root -h /var/www/html/intern

3.)

Then open nextcloud in a browser on your domain, register an admin user. Then config files got auto generated of which the next ones to modify are /var/www/html/.htaccess and /var/www/html/config/config.php

4.)

modify RewriteBase in /var/www/html/.htaccess where there was the following auto-generated code-block.

This step seems important as without it I get an ERR_TOO_MANY_REDIRECTS error.

#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####

ErrorDocument 403 /intern/
ErrorDocument 404 /intern/
<IfModule mod_rewrite.c>
  Options -MultiViews
  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]
  ....
  RewriteBase /intern # <-- changed from auto generated `RewriteBase /`
  ....
</IfModule>

5.)

Now it would work mostly already, except for the fact that the web login and client authentication form hang. This issue is discussed here: nextcloud/server#19091 and to fix it, add the following to /var/www/html/config/config.php:

...
'overwriteprotocol' => 'https' 
...

Now it's all working fine.

My current nextcloud version is 19 and traefik is v2.2

@timonf
Copy link

timonf commented Nov 7, 2020

It worked for me using the following lines:

docker-compose.yml:

  cloud_server:
    environment:
      - OVERWRITEWEBROOT=/cloud

and config.php:

  'htaccess.RewriteBase' => '/cloud',

...and running docker-compose exec -uwww-data cloud_server php occ maintenance:update:htaccess (after updating config.php)

Would be nice to have an env variable for htaccess.RewriteBase to have a clean setup without calling occ manually. Something like OVERWRITEHTACCESSBASE (or something more readable :D)?

PS.: Also @ettingshausen's link was very useful by adding rewrite ^/cloud(.*) $1 break; to my proxy's config 😊

@Michael-Hennemann
Copy link

@timonf Hi! I tried the 3 steps from your post

  • OVERWRITEWEBROOT variable in compose file
  • change config.php
  • run the command

but the "docker-compose exec " command is not working for me.

Nextcloud is not installed - only a limited number of commands are available
There are no commands defined in the "maintenance:update" namespace.
Did you mean this?
maintenance

Any idea?

cheers
michael

@SigiSang
Copy link

SigiSang commented Apr 28, 2021

Try this:
https://github.com/nextcloud/nextcloud-snap/wiki/Putting-the-snap-behind-a-reverse-proxy#nginx-optional-custom-path-location-for-reverse-proxy
It worked for me.

This was a big help to me, I was experiencing redirect loops (HTTP 302) as soon as I added overwritewebroot in nextcloud's config.php and had my reverse proxy redirect to nextcloud for location /nextcloud instead of /.
My setup: nextcloud runs in a docker container on one host and a Nginx reverse proxy forwards traffic for location /nextcloud.

To enable the reverse proxy I follow the nextcloud docs:
https://docs.nextcloud.com/server/19/admin_manual/configuration_server/reverse_proxy_configuration.html
I added these lines to nextclouds config.php, as described in the example at the bottom:

  'trusted_proxies'   => ['10.0.0.1'],
  'overwritehost'     => 'ssl-proxy.tld',
  'overwriteprotocol' => 'https',
  'overwritewebroot'  => '/domain.tld/nextcloud',
  'overwritecondaddr' => '^10\.0\.0\.1$',

Then setup nginx as a reverse proxy as follows:
https://github.com/nextcloud/nextcloud-snap/wiki/Putting-the-snap-behind-a-reverse-proxy#nginx-optional-custom-path-location-for-reverse-proxy

location /domain.tld/nextcloud {
     return 301 $scheme://$server_name/domain.tld/nextcloud/;
}
location /domain.tld/nextcloud/ {
   rewrite ^/domain.tld/nextcloud(.*) $1 break;
   proxy_pass http://host_with_docker;
}

The rewrite line was key here, I scowered a lot of guides & forums with similar setups, but this was the first time the rewrite was mentioned.
You also need to forward /domain.tld/nextcloud to /domain.tld/nextcloud/ to make it a bit more user friendly.
Putting everything under location /domain.tld/nextcloud instead of the forwarding breakes the rewrite in the edge case of visiting /domain.tld/nextcloud, because $1 is emtpy and the proxy throws an error: the rewritten URI has a zero length

@brendan-mccoy
Copy link

brendan-mccoy commented May 4, 2021

Anyone care to help me out? I get constant 302s after creating my admin account, no matter what I do. Here's a post I was going to post to the forums, but it kept rejecting my post :/ Google proved to me the forums are useless anyway, this topic is on there constantly with zero responses.

I am trying to setup nextcloud on a subdirectory (example.com/nextcloud). I can get to the initial setup screen (where I create an admin account), but after pressing enter after entering my new password, I can only get a 302 message on example.com/nextcloud.

Here is my docker-compose.yml for nextcloud and its db, modified slightly from https://github.com/nextcloud/docker#base-version---fpm

 version: '2'
 
 services: 
   db:
     image: mariadb
     restart: always
     command: --transaction-isolation=READ-COMMITTED --binlog-format=ROW
     volumes:
       - ./db:/var/lib/mysql
 
     environment:
       - MYSQL_ROOT_PASSWORD=ROOTPASS 
       - MYSQL_PASSWORD=PASS
       - MYSQL_DATABASE=nextcloud
       - MYSQL_USER=nextcloud
 
   app:
     image: nextcloud:production-fpm-alpine
     restart: always
     links:
       - db
     ports:
       - 9000:9000
 
     volumes:
       - ./app:/var/www/html
 
     environment:
       - MYSQL_PASSWORD=PASS
       - MYSQL_DATABASE=nextcloud
       - MYSQL_USER=nextcloud
       - MYSQL_HOST=db
       - OVERWRITEWEBROOT=/nextcloud

I expose port 9000 since my nginx instance is in a different docker-compose.yml. It mounts the same .app directory at /var/www/html/nextcloud.

Here is my config for nginx, modified from https://docs.nextcloud.com/server/stable/admin_manual/installation/nginx.html#nextcloud-in-a-subdir-of-the-nginx-webroot

server {
    listen DOCKERHOST:443 ssl http2;
    # listen [::]:443 ssl http2;

    # snippet sets certs
    include snippets/domain_example.com.conf;

    server_name example.com www.example.com *.example.com;

    root /var/www;

    # snippets set ssl configs, "custom" errors, security.txt
    include snippets/https.conf;
    include snippets/errors.conf;
    include snippets/security.txt.conf;

    location /.well-known {
        # The following 6 rules are borrowed from `.htaccess`

        rewrite ^/\.well-known/host-meta\.json  /nextcloud/public.php?service=host-meta-json    last;
        rewrite ^/\.well-known/host-meta        /nextcloud/public.php?service=host-meta         last;
        rewrite ^/\.well-known/webfinger        /nextcloud/public.php?service=webfinger         last;
        rewrite ^/\.well-known/nodeinfo         /nextcloud/public.php?service=nodeinfo          last;

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

        try_files $uri $uri/ =404;
    }

    location ^~ /nextcloud {
        # 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;

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

        # Specify how to handle directories -- specifying `/nextcloud/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/ /nextcloud/index.php$request_uri`
        # always provides the desired behaviour.
        index index.php index.html /nextcloud/index.php$request_uri;

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

        # Rules borrowed from `.htaccess` to hide certain paths from clients
        location ~ ^/nextcloud/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/)    { return 404; }
        location ~ ^/nextcloud/(?:\.|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
        # `/nextcloud/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 DOCKERHOST:9000;

            fastcgi_intercept_errors on;
            fastcgi_request_buffering off;
        }

        location ~ \.(?:css|js|svg|gif)$ {
            try_files $uri /nextcloud/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 /nextcloud/index.php$request_uri;
            expires 7d;         # Cache-Control policy borrowed from `.htaccess`
            access_log off;     # Optional: Don't log access to assets
        }

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

At this point, I've done what the docs say to do, and get a 404, presented to the client and also logged on the Nextcloud container:

"GET /nextcloud/index.php" 404

Then, I try #401 (comment).

ln -s /var/www/html/ /var/www/nextcloud
chown www-data:root -h /var/www/nextcloud

After the above, (I used /var/www/nextcloud instead of /var/www/html/nextcloud because the nextcloud site docs used /var/www as the root instead of /var/www. Doing it any other way continues 404s).

So, I get a one time success! I am presented with a screen to create an admin (this shows I'm getting the styles/assets from my proxy). I create an account, and then configuration files are generated (Showing my proxy is reaching the nextcloud server correctly). But... Now I just constantly get 302s! Performing the rest of the steps in the github link doesn't change the constant 302s (that also log on nextcloud).

After step 3 of the linked comment, my config.php that was generated looks like this:

<?php
$CONFIG = array (
  'memcache.local' => '\\OC\\Memcache\\APCu',
  'apps_paths' => 
  array (
    0 => 
    array (
      'path' => '/var/www/html/apps',
      'url' => '/apps',
      'writable' => false,
    ),
    1 => 
    array (
      'path' => '/var/www/html/custom_apps',
      'url' => '/custom_apps',
      'writable' => true,
    ),
  ),
  'overwritewebroot' => '/nextcloud',
  'instanceid' => 'REDACTED',
  'passwordsalt' => 'REDACTED',
  'secret' => 'REDACTED',
  'trusted_domains' => 
  array (
    0 => 'example.com',
  ),
  'datadirectory' => '/var/www/html/data',
  'dbtype' => 'mysql',
  'version' => '20.0.9.1',
  'overwrite.cli.url' => 'https://example.com/nextcloud',
  'dbname' => 'nextcloud',
  'dbhost' => 'db',
  'dbport' => '',
  'dbtableprefix' => 'oc_',
  'mysql.utf8mb4' => true,
  'dbuser' => 'nextcloud',
  'dbpassword' => 'PASS',
  'installed' => true,
);

My .htaccess (after manually adding the rewritebase line)

<IfModule mod_headers.c>
  <IfModule mod_setenvif.c>
    <IfModule mod_fcgid.c>
       SetEnvIfNoCase ^Authorization$ "(.+)" XAUTHORIZATION=$1
       RequestHeader set XAuthorization %{XAUTHORIZATION}e env=XAUTHORIZATION
    </IfModule>
    <IfModule mod_proxy_fcgi.c>
       SetEnvIfNoCase Authorization "(.+)" HTTP_AUTHORIZATION=$1
    </IfModule>
  </IfModule>

  <IfModule mod_env.c>
    # Add security and privacy related headers

    # Avoid doubled headers by unsetting headers in "onsuccess" table,
    # then add headers to "always" table: https://github.com/nextcloud/server/pull/19002
    Header onsuccess unset Referrer-Policy
    Header always set Referrer-Policy "no-referrer"

    Header onsuccess unset X-Content-Type-Options
    Header always set X-Content-Type-Options "nosniff"

    Header onsuccess unset X-Download-Options
    Header always set X-Download-Options "noopen"

    Header onsuccess unset X-Frame-Options
    Header always set X-Frame-Options "SAMEORIGIN"

    Header onsuccess unset X-Permitted-Cross-Domain-Policies
    Header always set X-Permitted-Cross-Domain-Policies "none"

    Header onsuccess unset X-Robots-Tag
    Header always set X-Robots-Tag "none"

    Header onsuccess unset X-XSS-Protection
    Header always set X-XSS-Protection "1; mode=block"

    SetEnv modHeadersAvailable true
  </IfModule>

  # Add cache control for static resources
  <FilesMatch "\.(css|js|svg|gif)$">
    Header set Cache-Control "max-age=15778463"
  </FilesMatch>

  # Let browsers cache WOFF files for a week
  <FilesMatch "\.woff2?$">
    Header set Cache-Control "max-age=604800"
  </FilesMatch>
</IfModule>
<IfModule mod_php7.c>
  php_value mbstring.func_overload 0
  php_value default_charset 'UTF-8'
  php_value output_buffering 0
  <IfModule mod_env.c>
    SetEnv htaccessWorking true
  </IfModule>
</IfModule>
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_USER_AGENT} DavClnt
  RewriteBase /nextcloud
  RewriteRule ^$ /remote.php/webdav/ [L,R=302]
  RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
  RewriteRule ^\.well-known/host-meta /public.php?service=host-meta [QSA,L]
  RewriteRule ^\.well-known/host-meta\.json /public.php?service=host-meta-json [QSA,L]
  RewriteRule ^\.well-known/webfinger /public.php?service=webfinger [QSA,L]
  RewriteRule ^\.well-known/nodeinfo /public.php?service=nodeinfo [QSA,L]
  RewriteRule ^\.well-known/carddav /remote.php/dav/ [R=301,L]
  RewriteRule ^\.well-known/caldav /remote.php/dav/ [R=301,L]
  RewriteRule ^remote/(.*) remote.php [QSA,L]
  RewriteRule ^(?:build|tests|config|lib|3rdparty|templates)/.* - [R=404,L]
  RewriteCond %{REQUEST_URI} !^/\.well-known/(acme-challenge|pki-validation)/.*
  RewriteRule ^(?:\.|autotest|occ|issue|indie|db_|console).* - [R=404,L]
</IfModule>
<IfModule mod_mime.c>
  AddType image/svg+xml svg svgz
  AddEncoding gzip svgz
</IfModule>
<IfModule mod_dir.c>
  DirectoryIndex index.php index.html
</IfModule>
AddDefaultCharset utf-8
Options -Indexes
<IfModule pagespeed_module>
  ModPagespeed Off
</IfModule>
#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####

ErrorDocument 403 /nextcloud/
ErrorDocument 404 /nextcloud/

@SigiSang
Copy link

SigiSang commented May 4, 2021

So if I understand correctly you have an Nginx reverse proxy in one docker container and nextcloud in another? In that case, I notice you don't have any nextcloud configuration for the reverse proxy (see my previous post, the one before yours).
I think at least 'trusted_proxies' is required. I'm guessing the IP there needs to be the IP of your host machine, as the docker-containers come from separate docker-compose file ergo are in different docker networks.

I have set up an Nginx reverse proxy on one machine, pointing /nextcloud to a docker container on another. I didn't need to change .htaccess or create a symlink, only change the nextcloud config for reverse proxy per the docs and correctly rewrite the url with the proxy configuration in Nginx (reverse proxy, not nextclouds own Nginx instance).

P.S. Rereading your comment I'm starting to think you're trying to run nextcloud through Nginx in a different container (judging from your volume mounts), which would be very weird as the nextcloud container hosts its own Nginx instance. Is this the case?

@brendan-mccoy
Copy link

I am using the fpm image, which does not have its own nginx instance. Adding trusted proxies docker environment variable (which adds it to the config) doesn't change the behavior.

@SigiSang
Copy link

SigiSang commented May 4, 2021

Right, if you're just running the single nginx instance you don't need the reverse proxy config. I was misguided because you mentioned 'proxy' in your comment, but in your case it's just a single nginx hosting the files from within the nextcloud container.

Have you checked the logs of nginx to find any clue as to why throws 302?

@brendan-mccoy
Copy link

Nginx logs:
"GET /nextcloud HTTP/2.0" 301
"GET /nextcloud/ HTTP/2.0" 302

Nextcloud logs:
"GET /nextcloud/index.php" 302

I don't really see anything else unfortunately. I will try to see if maybe there's a higher level of logging for nextcloud.

@brendan-mccoy
Copy link

Alright, it was custom 301/302 responses on nginx breaking it. That's why everything looks completely errorless.

@brendan-mccoy
Copy link

An updated image has broken this =/

@sethidden
Copy link

What stopped the "This page isn't redirecting correctly" error for me was:

//config.php
<?php
$CONFIG = array (
  'htaccess.RewriteBase' => '/',
  'overwriteprotocol' => 'https',
  'overwritehost' => 'mysubdomain.mywebsite.com', //you can obviously use just mywebsite.com
  'overwritewebroot' => '/nextcloud',
  // ... defaults here
//nginx
location /nextcloud/ {
                proxy_pass http://localhost:2137/;
        }

Note: I did not apply the RewriteBase /nextcloud fix recommended above

The most important part here is pobably the https override. I think nextcloud may be redirecting to a http URL, but then nextcloud upgrades the link to https, and then it goes back to http and so on.

Adding the http override also forces you to add the overwritehost because otherwise you'll be redirected to localhost:2137 for some reason

@jscmidt
Copy link

jscmidt commented Mar 3, 2022

vi <local_mount_point>/html/.htaccess add or change "RewriteBase /" to "RewriteBase /your-sub-context" vi <local_mount_point>/html/config/config.php add 'overwritewebroot' => '/your-sub-context', cd <local_mount_point>/html/ ln -s ../html/ your-sub-context

This one (which is almost the same as many other tutorials posted here) is working for me.
However, I have to do all the steps again every time I update the container (new image), which is really annoying. Has anybody the same problem and found a solution to keep the changes persistent?

@huangqinjin
Copy link

vi <local_mount_point>/html/.htaccess add or change "RewriteBase /" to "RewriteBase /your-sub-context"

One thing worth mentioning here is that the actual config used are gathered from config/*.config.php and config/config.php. And htaccess.RewriteBase is by default located in two files : config/config.php and config/apache-pretty-urls.config.php. So to avoid manually modify .htaccess, you need change the setting in both files.

@ArtemSmaznov
Copy link

Maybe a stupid question but why does the official docker image default to /var/www/html when all the docs pages regarding installation I have seen reference /var/www/nextcloud as default install path?
I am referring mostly to these:
https://docs.nextcloud.com/server/latest/admin_manual/installation/source_installation.html
https://docs.nextcloud.com/server/latest/admin_manual/installation/nginx.html

It seems to me like a lot of issues stems from this discrepancy. I am basing my setup on the following example from this repo and I have been struggling to set nextcloud to run in subdir. I have managed to get it to work for the most part but I cannot use occ as it still points to /var/www/html while my installation runs from /var/www/nextcloud
https://github.com/nextcloud/docker/tree/master/.examples/docker-compose/with-nginx-proxy/mariadb/fpm

I have spent a bunch of time today clearing volumes and rebuilding images from docker compose trying to get a fresh installation to go to /var/www/nextcloud on the app container but it simply continues to go html

@dstroinski
Copy link

Because I also faced this problem, here's what worked for me on docker + nextcloud:25.0-apache.

  1. docker-compose.yml - mounted volume /data/nextcloud/app
  app:
    image: nextcloud:25.0-apache
    ...
    volumes:
      - /data/nextcloud/app:/var/www/html
  1. verify nexclodud is accessible from local IP (127.0.0.1:PORT or 192.168.x.x:PORT), create admin account, proceed with initial setup

  2. add your domain to trusted_domains (example.com in this case)

# nano /data/nextcloud/app/config/config.php

'trusted_domains' =>
array (
  0 => ...,
  1 => 'example.com',
),
  1. change htaccess.RewriteBase from / to /yoursubdirectory
# nano /data/nextcloud/app/config/config.php

'htaccess.RewriteBase' => '/yoursubdirectory',
  1. add overwritewebroot to $CONFIG
# nano /data/nextcloud/app/config/config.php

... at the end of the file:
  'installed' => true,
  'overwritewebroot'  => '/yoursubdirectory',
);
  1. change htaccess.RewriteBase from / to /yoursubdirectory
# nano /data/nextcloud/app/config/apache-pretty-urls.config.php

'htaccess.RewriteBase' => '/yoursubdirectory',
  1. update .htaccess with occ
# docker exec --user www-data nextcloud-app-1 php occ maintenance:update:htaccess

NOTE: nextcloud-app-1 is a container name
  1. create symbolic link
# cd /data/nextcloud/app
# ln -s . yoursubdirectory

And that's it. Now nextcloud should be accessible on http://127.0.0.1:PORT/yoursubdirectory or http://192.168.x.x:PORT/yoursubdirectory, setting up traefik requires adding

- "traefik.http.routers.nextcloud.rule=Host(`example.com`) && PathPrefix(`/yoursubdirectory`)"

@obel1x
Copy link

obel1x commented May 25, 2023

i am struggling with the same question. could anyone please help an get a working updated version here?

i tried that Docker- Image: https://github.com/nextcloud/docker/tree/master/.examples/docker-compose/with-nginx-proxy/postgres/fpm
when installing it as described here https://github.com/nextcloud/docker/tree/master/.examples#with-nginx-proxy all runs fine on the server.

Then i want to move this installation to /nextcloud subdirectory and add some new Service to the top- page of a different docker-image.

I tried to use in .yaml / web:
VIRTUAL_PATH=/nextcloud
VIRTUAL_DEST=/

than set in nextcloud config.php:
overwritehost
overwriteprotocol
overwritewebroot
overwrite.cli.url
and ran occ to update .htaccess

That way, the server works with the given subdirectory basically (nextcloud page shows). I know, there are a lot of options above, but i either could not find them in my setup, or they would not work.

But first i do not understand how to add different services to that configuration. I would expect the nginx- proxy to be configured to redirect / to another container-service. But i have not found a config file for the proxy. How do i do that with this setup? (BTW i don't want to move files in /var/www/html to /var/www/html/nextcloud as this may destroy data in the future as described by some users).

Second - maybe related to this: .wellknown won't work and either redirects to non-subdirectory (webfinger) or to nothing (caldav, carddav). So where to adjust those links now? Maybe just a hint missing how to configure nging- proxy in that setup.

Last, there is a strange error accessing many links, e.g. webdav will not work at all and files cannot be accessed at all. The error message ist like: "Requested uri (/nextcloud/remote.phpp/webdav) is out of base uri (/nextcloud/remote.php/webdav/)"

There seems to be a "p" inserted in remote.phpp, which wont work, making t impossible to access files at all.

Could anybody explain how to do this right?

@stefangweichinger
Copy link

stefangweichinger commented Dec 26, 2023

Let me also add my problems to this thread:

I am in the progress from nginx (on the host) to traefik (in docker) as rev-proxy.

My nextcloud is running in a subdir because of historical reasons. For now I would like to keep it like that to not break calendar-URLs etc ( think "wife acceptance factor" here ... wife and phone away right now because of holidays etc).

I fiddle with various settings and don't get it working.

configs

nc docker-compose
  app:
    image: nextcloud:28
    depends_on:
      - db
      - redis
    ports:
      - '8084:80'
    volumes:
      - app:/var/www/html
      - custom_apps:/var/www/html/custom_apps
      - data:/var/www/html/data
    environment:
      MYSQL_HOST: db
      TRUSTED_PROXIES: '172.20.0.0/16 172.31.60.1'
      OVERWRITEPROTOCOL: https
      OVERWRITECLIURL: 'https://oc.oops.co.at/nextcloud'
      OVERWRITEHOST: oc.oops.co.at
      OVERWRITEWEBROOT: '/nextcloud'
    env_file:
      - db.env
    labels:
      traefik.docker.network: proxy
      traefik.enable: "true"
        #traefik.http.middlewares.nextcloud-dav.replacepathregex.regex: ^/.well-known/ca(l|rd)dav
        #traefik.http.middlewares.nextcloud-dav.replacepathregex.replacement: /remote.php/dav/
      traefik.http.routers.nextcloud.entrypoints: websecure
        #traefik.http.routers.nextcloud.middlewares: nextcloud-dav,default@file
      traefik.http.routers.nextcloud.middlewares: nextcloud_redirectregex,default@file
      traefik.http.middlewares.nextcloud_redirectregex.redirectregex.permanent: true
      traefik.http.middlewares.nextcloud_redirectregex.redirectregex.regex: 'https://(.*)/.well-known/(?:card|cal)dav'
      traefik.http.middlewares.nextcloud_redirectregex.redirectregex.replacement: 'https://$${1}/remote.php/dav'
      traefik.http.routers.nextcloud.rule: 'Host(`oc.oops.co.at`) && PathPrefix(`/nextcloud`)'
      traefik.http.routers.nextcloud.service: nextcloud
      traefik.http.routers.nextcloud.tls: "true"
      traefik.http.routers.nextcloud.tls.certresolver: http_resolver
      traefik.http.services.nextcloud.loadbalancer.server.port: "80"
    networks:
      - nextcloud__internal
      - proxy
      - default
    restart: always
nc config.php
  'trusted_proxies' => 
  array (
    0 => '172.20.0.0/16',
    1 => '172.31.60.1',
  ),
  'overwritehost' => 'oc.oops.co.at',
  'overwriteprotocol' => 'https',
  'overwrite.cli.url' => 'https://oc.oops.co.at/nextcloud',
  'htaccess.RewriteBase' => '/nextcloud',
  'overwritewebroot' => '/nextcloud',

Yes, some redundancy there because of my fiddling.
Maybe too much settings ... getting lost already.

Whenever I access https://oc.oops.co.at/nextcloud I get a nc-page saying "page not found" and 404-errors in traefik logs

62.40.171.237 - - [26/Dec/2023:16:56:04 +0000] "GET /nextcloud/index.php/204 HTTP/1.1" 404 5010 "-" "-" 4155 "nextcloud@docker" "http://172.31.60.2:80" 83ms
62.40.171.237 - - [26/Dec/2023:16:56:04 +0000] "GET /nextcloud/index.php/204 HTTP/1.1" 404 5008 "-" "-" 4156 "nextcloud@docker" "http://172.31.60.2:80" 46ms
62.40.171.237 - - [26/Dec/2023:16:56:04 +0000] "GET /nextcloud/status.php HTTP/1.1" 404 5009 "-" "-" 4157 "nextcloud@docker" "http://172.31.60.2:80" 44ms
62.40.171.237 - - [26/Dec/2023:16:56:04 +0000] "GET /nextcloud/nextcloud/status.php HTTP/1.1" 404 5008 "-" "-" 4158 "nextcloud@docker" "http://172.31.60.2:80" 48ms

Is it maybe related to PHP? Do I need the FPM-image maybe .. now that nginx with fpm isn't in place anymore?
Any help welcome and appreciated!

EDIT:

some more observations:

tried to access the nc-container from the shell:

  wget http://172.31.60.5:80/index.php
--2023-12-26 18:46:56--  http://172.31.60.5/index.php
Connecting to 172.31.60.5:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://172.31.60.5/index.php [following]
--2023-12-26 18:46:56--  https://172.31.60.5/index.php
Connecting to 172.31.60.5:443... failed: Connection refused.

So there is some http->https redirection tried here.
As far as I understand that must happen in the nextcloud-container as I access its IP directly(?)
toggled "forcessl" in `config.php ... that removes the redirection but still 404:

wget http://172.31.60.2:80/nextcloud/index.php
--2023-12-26 18:55:39--  http://172.31.60.2/nextcloud/index.php
Connecting to 172.31.60.2:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2023-12-26 18:55:39 ERROR 404: Not Found.

EDIT 2:

current state:

# wget http://172.31.60.2/nextcloud/apps/theming/css/default.css
--2023-12-26 21:01:41--  http://172.31.60.2/nextcloud/apps/theming/css/default.css
Connecting to 172.31.60.2:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2023-12-26 21:01:41 ERROR 404: Not Found.

# wget http://172.31.60.2/apps/theming/css/default.css
--2023-12-26 21:01:46--  http://172.31.60.2/apps/theming/css/default.css
Connecting to 172.31.60.2:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3774 (3.7K) [text/css]
Saving to: ‘default.css’

default.css                                        100%[=============================================================================================================>]   3.69K  --.-KB/s    in 0s      

2023-12-26 21:01:46 (202 MB/s) - ‘default.css’ saved [3774/3774]

SOLVED by following https://community.traefik.io/t/https-routing-404-page-not-found-docker-file/19561/9

@bdovaz
Copy link

bdovaz commented Jun 17, 2024

@StokeHead @m00nwtchr @SteffRhes @dstroinski

I have tried all variants of these symlink solutions and in versions like 25 it works but in 28 or 29 it doesn't work? Does anyone know why? Seems like a regression

The errors in the screenshot occur just when I click on a file, as in this case, an image.

Errors on the server:

The requested uri(/apps/files/api/v1/stats) cannot be processed by the script '/yoursubdirectory/index.php')

image

@joshtrichards
Copy link
Member

There is no need to move files around in the image or do anything weird.

All that is needed:

  • a web server configured in the standard manner for Nextcloud
  • a decent, modern reverse proxy platform (Nginx, Caddy should work; I'd expect Traefik as well though I've not tested it)
  • setting OVERWRITEWEBROOT
  • enabling path (URI) stripping on the reverse proxy

See #2276 for a working example for reverse proxies { Caddy or Nginx } with the FPM image.

@joshtrichards joshtrichards added the needs info Additional info needed to triage label Oct 15, 2024
@joshtrichards
Copy link
Member

Closing since there's nothing left to do here. If we opt to add any formal documentation (TBD), it'll be tracked through #2276. If anyone wishes to test the configurations noted in that Issue, please do so there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cleanup (ignore): subs examples Compose/Dockerfile/etc integration: proxy Integrating with a reverse proxy needs info Additional info needed to triage needs review Needs confirmation this is still happening or relevant question
Projects
None yet
Development

No branches or pull requests