Reverse proxy with nginx remapping the root folder Ubuntu 24.04

I have a Nginx reverse proxy running on my Manjaro installation that I have been running for years. I decided to spin up a VM with the new Ubuntu server 24.04 and install Nextcloud, as it is super easy with the new system and runs straight out of the box using the snap package.

I have run it initially in the VM through localhost and everything is running smoothly. I then went through the documentation and found the Nginx reverse proxy config for serving from a subdir.

The problem I’m getting is that when I use 'overwritewebroot' => '/nextcloud', in the config.php file, I get a 404 on localhost. It maps the /nextcloud folder into the URL, but can’t find anything. If I remove the line from config.php and restart Nextcloud it works again on localhost, but still a 404 on the reverse proxy.

Here is the config.php without the 'overwritewebroot' => '/nextcloud', line

$CONFIG = array (
  'apps_paths' => 
  array (
    0 => 
    array (
      'path' => '/snap/nextcloud/current/htdocs/apps',
      'url' => '/apps',
      'writable' => false,
    1 => 
    array (
      'path' => '/var/snap/nextcloud/current/nextcloud/extra-apps',
      'url' => '/extra-apps',
      'writable' => true,
  'supportedDatabases' => 
  array (
    0 => 'mysql',
  'memcache.locking' => '\\OC\\Memcache\\Redis',
  'memcache.local' => '\\OC\\Memcache\\Redis',
  'redis' => 
  array (
    'host' => '/tmp/sockets/redis.sock',
    'port' => 0,
  'log_type' => 'file',
  'logfile' => '/var/snap/nextcloud/current/logs/nextcloud.log',
  'logfilemode' => 416,
  'instanceid' => 'ocqjzyg6i88y',
  'passwordsalt' => 'aOhYBGKBIlOh4/reisw/5o9JuUPjmk',
  'secret' => '771Pw2HiBcxK9jNIFDxb8I9S/Q8kMKPgm/ACXIZ3LPIvvdxq',
  'trusted_domains' => 
  array (
    0 => 'localhost', // VM
    1 => '', // Reverse Proxy
    2 => '', // VM
    3 => 'fe80::5054:ff:fefa:d806', // VM
  'trusted_proxies' => 
  array (
    0 => '', // Reverse Proxy
  'forwarded_for_headers' => 
  array (
  'datadirectory' => '/var/snap/nextcloud/common/nextcloud/data',
  'dbtype' => 'mysql',
  'version' => '',
  'dbname' => 'nextcloud',
  'dbhost' => 'localhost:/tmp/sockets/mysql.sock',
  'dbport' => '',
  'dbtableprefix' => 'oc_',
  'mysql.utf8mb4' => true,
  'dbuser' => 'nextcloud',
  'dbpassword' => 'u9k9OEI1b46qGRdU9Ejwczi_YwGUahACkDjOs18t1O2SKZg-KD0Qsfcd23WZVVkl',
  'installed' => true,
  'maintenance' => false,
  'loglevel' => 2,
  'maintenance_window_start' => 1,

I used the example config for Nginx from this link:
Nextcloud in a subdir of the NGINX webroot

Here is my Nginx config for the reverse proxy:

upstream php-handler {
    #server unix:/run/php/php8.2-fpm.sock;

# Set the `immutable` cache control options only for assets with a cache busting `v` argument
map $arg_v $asset_immutable {
    "" "";
    default ", immutable";

server {
    if ($host = {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    return 404; # managed by Certbot

    # Prevent nginx HTTP Server Detection
    server_tokens off;

    # Enforce HTTPS just for `/nextcloud`
    location /nextcloud {
        return 301 https://$server_name$request_uri;

server {
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    # Root
    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $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;

    # Jellyfin
    location /jellyfin {
        return 302 $scheme://$host/jellyfin/;

    location /jellyfin/ {
        # Proxy main Jellyfin traffic

        # The / at the end is significant.


        proxy_pass_request_headers on;

        proxy_set_header Host $host;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $http_host;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $http_connection;

        # Disable buffering when the nginx proxy gets very resource heavy upon streaming
        proxy_buffering off;

    # Prevent nginx HTTP Server Detection
    server_tokens off;

    # Set .mjs and .wasm MIME types
    # Either include it in the default mime.types list
    # and include that list explicitly or add the file extension
    # only for Nextcloud like below:
    include mime.types;
    types {
        text/javascript mjs;
	application/wasm wasm;

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

    location ^~ /.well-known {
        # The rules in this block are an adaptation of the rules
        # in the Nextcloud `.htaccess` that concern `/.well-known`.

        location = /.well-known/carddav { return 301 /nextcloud/remote.php/dav/; }
        location = /.well-known/caldav  { return 301 /nextcloud/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 /nextcloud/index.php$request_uri;

    location /nextcloud {
	rewrite ^/nextcloud(/.*)$ $1 break;
    	proxy_set_header Host $host;
    	proxy_set_header X-Real-IP $remote_addr;
    	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    	proxy_set_header X-Forwarded-Proto https;

        # set max upload size and increase upload timeout:
        client_max_body_size 512M;
        client_body_timeout 300s;
        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 text/javascript application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/ application/wasm 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;

        # The settings allows you to optimize the HTTP2 bandwidth.
        # See
        # for tuning hints
        client_body_buffer_size 512k;

        # HSTS settings
        # WARNING: Only add the preload option once you read about
        # the consequences in 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;

        # 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-Frame-Options                   "SAMEORIGIN"        always;
        add_header X-Permitted-Cross-Domain-Policies "none"              always;
        add_header X-Robots-Tag                      "noindex, nofollow" 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`, `/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(?:$|/) {
            # Required for legacy support
            rewrite ^/nextcloud/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|ocs-provider\/.+|.+\/richdocumentscode(_arm64)?\/proxy) /nextcloud/index.php$request_uri;

            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;

            fastcgi_max_temp_file_size 0;

        # Serve static files
        location ~ \.(?:css|js|mjs|svg|gif|png|jpg|ico|wasm|tflite|map|ogg|flac)$ {
            try_files $uri /nextcloud/index.php$request_uri;
            # HTTP response headers borrowed from Nextcloud `.htaccess`
            add_header Cache-Control                     "public, max-age=15778463$asset_immutable";
            add_header Referrer-Policy                   "no-referrer"       always;
            add_header X-Content-Type-Options            "nosniff"           always;
            add_header X-Frame-Options                   "SAMEORIGIN"        always;
            add_header X-Permitted-Cross-Domain-Policies "none"              always;
            add_header X-Robots-Tag                      "noindex, nofollow" always;
            add_header X-XSS-Protection                  "1; mode=block"     always;
            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

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

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

The reverse proxy works with everything apart from Nextcloud.

Has anyone got any ideas on why the folder would not be rewriting the root of Nextcloud, even without the reverse proxy?

First of all, that Nginx configuration is for when Nginx is the web server not just a reverse proxy. There is an actual chapter on reverse proxy and the Nginx config is like 4 lines. :slight_smile:

Next up, you’re using the Snap. It has its own way of doing things:

1 Like

@jtr is right @Coopertronics

Quick look at your nginx config - for reverse proxy you need to do the same thing you do with Jellyfin, just specify location (ie where related to webroot it will be served from ) and then proxy_pass to your nextcloud instance. Keep in mind the snap specifics.

What you got in your nginx config is a web serving config, but I can’t see where you specify the reverse proxy for /nextcloud.

I’d suggest to take it step by step, and also clean up a bit - make a separate site config file just for nextcloud, do the reverse proxy first + certificates, try if it works, and then add all the other desired stuff.


Thanks @jtr and @LeoStehlik, I am getting a little further now. I decided to install Ubuntu server 24.04 on bare metal and I have the reverse proxy running on a different machine, also bare metal.

The GitHub page that @jtr posted is very useful and was something I was looking for. I’m taking @LeoStehlik advice and starting from the bottom up and just doing everything step by step.

The first thing I want to do is get the nextcloud snap running from localhost or the dedicated machines IP from a sub folder like this:


This is as far as I have got. I am unable to get it to give me anything other than a 404, but it does recognise the change, sort of. It gives me the URL: http://localhost:8090/nextcloud/index.php/login which it is supposed to do, but I get a 404.

I can only assume that I am missing something in the initial setup.
Here is what I have added to the config.php

  'trusted_domains' => 
  array (
    0 => 'localhost',
    1 => '', // IP address of localhost
  'overwritewebroot' => '/nextcloud', // The subdir I want to serve from
  'overwrite.cli.url' => '', // The URL to serve from
  'htaccess.RewriteBase' => '/nextcloud', // The subdir I want to serve from

If I understand the instructions correctly then this is all I should need to get Nextcloud to run from a subdir. The reverse proxy works with Jellyfin, another apache instance running on a different machine and a basic website running on another Apache instance, but unless I can get Nextcloud to actually serve on the subdir from localhost there will be no point even thinking about using the reverse proxy.

I am going to try installing next cloud in an Arch VM without using snaps or flatpak just to see if I get the same results.

If you have any ideas why the subdir is simply not working on localhost then please let me know. I will be very grateful.