Files

File sharing and management

File Sharing

Nextcloud users can share files with their Nextcloud groups and other users on the same Nextcloud server, with Nextcloud users on other Nextcloud servers, and create public shares for people who are not Nextcloud users. You have control of a number of user permissions on file shares.

Configure your sharing policy on your Admin page in the Sharing section.

With Default share permissions you are able to set the default permissions for user-shares (Create, Change, Delete and Reshare) without forcing them.

提示

Nextcloud does not preserve the mtime (modification time) of directories, though it does update the mtimes on files. See Wrong folder date when syncing for discussion of this.

提示

There are more sharing options on config.php level available: Configuration Parameters

Advanced settings

Here are some edge case settings which are not editable from the web interface, because they are only useful to small subset of administrators.

You can use the occ command to update those, for example:

occ config:app:set core shareapi_restrict_user_enumeration_full_match_email --value yes

Distinguish between max expiration date and default expiration date

The expiration date which can be set and enforced in the settings above are the hard limit and the default value at the same time. Sometimes admins want to have a moderate default expire date, for example 7 days but make sure that the user can't extend it to more than 14 days.

In order to do so, set a enforced expiration date in the settings as described above and set the default value to something below the maximal possible expiration date with the following OCC commands:

occ config:app:set --value <DAYS> core internal_defaultExpDays
occ config:app:set --value <DAYS> core link_defaultExpDays

Get a notification before a share expires

Users can get a notification before a share expires. In order to do so a cronjob need to be configured which calls the following OCC command once a day:

occ sharing:expiration-notification

A notification will be send for all shares which expire within the next 24 hours.

Transferring files to another user

You may transfer files from one user to another with occ. This is useful when you have to remove a user. Be sure to transfer the files before you delete the user! This transfers all files from user1 to user2, and the shares and metadata info associated with those files (shares, tags, comments, etc). Trashbin contents are not transferred:

occ files:transfer-ownership user1 user2

(See Using the occ command for a complete occ reference.)

Users may also transfer files or folders selectively by themselves. See user documentation for details.

Creating persistent file Shares

When a user is deleted, their files are also deleted. As you can imagine, this is a problem if they created file shares that need to be preserved, because these disappear as well. In Nextcloud files are tied to their owners, so whatever happens to the file owner also happens to the files.

One solution is to create persistent shares for your users. You can retain ownership of them, or you could create a special user for the purpose of establishing permanent file shares. Simply create a shared folder in the usual way, and share it with the users or groups who need to use it. Set the appropriate permissions on it, and then no matter which users come and go, the file shares will remain. Because all files added to the share, or edited in it, automatically become owned by the owner of the share regardless of who adds or edits them.

Using File Drop Share links

Using a File Drop Share allows users to upload files to Nextcloud through an unauthenticated session. File Drop Share links will only work when Allow public uploads is checked in the Sharing section of the Administration Settings page.

提示

File Drop Shares currently have a limitation in that any files uploaded through an unauthenticated session will not be chunked. Therefore the maximum file size that can be uploaded through File Drop Shares depends entirely on settings set within your environment.

Configuring Federation Sharing

Federated Cloud Sharing is now managed by the Federation app (9.0+), and is now called Federation sharing. When you enable the Federation app you can easily and securely link file shares between Nextcloud servers, in effect creating a cloud of Nextclouds.

Creating a new Federation Share

Follow these steps to create a new Federation share between two Nextcloud servers. This requires no action by the user on the remote server; all it takes is a few steps on the originating server.

  1. Enable the Federation app.
  2. Go to your Nextcloud Admin page and scroll to the Sharing section. Verify that Allow users on this server to send shares to other servers and Allow users on this server to receive shares from other servers are enabled.
  3. Now go to the Federation section. The Federation app supports creating a list of trusted Nextcloud servers, which allows the trusted servers to exchange user directories and auto-complete the names of external users when you create shares.

  1. Now go to your Files page and select a folder to share. Click the share icon, and then enter the username and URL of the user on the remote Nextcloud server. In this example, that is freda@https://example.com/nextcloud. When Nextcloud verifies the link, it displays it with the (remote) label. Click on this label to establish the link.

You may disconnect the share at any time by clicking the trash can icon.

Configuring trusted Nextcloud servers

You may create a list of trusted Nextcloud servers for Federation sharing. This allows your linked Nextcloud servers to share user directories, and to auto-fill user names in share dialogs.

You may also enter Nextcloud server URLs in the Add Nextcloud Server field.

A red light means the connection failed. The yellow light indicates a successful connection, with no user names exchanged. The green light indicates a successful connection with user names exchanged.

The prerequisiste for a green status is that the trusted servers were maintained in both interacting Nextcloud servers. Additionally occ federation:sync-addressbooks must have been executed (part of cron job list). The delay to execute the cron is based on local configuration of the cron frequency.

Creating Federation Shares via public Link Share

You may optionally set a password and expiration date on it. When your recipient receives your email they must click the link, or copy it to a Web browser. They will see a page displaying a thumbnail of the file, with a button to Add to your Nextcloud.

Your recipient should click the Add to your Nextcloud button. On the next screen your recipient needs to enter the URL to their Nextcloud server, and then press the return key.

Your recipient has to take one more step, and that is to confirm creating the federated cloud share link by clicking the Accept button.

Un-check the Share link checkbox to disable any federated cloud share created this way.

Configuration tips

The Sharing section on your Admin page allows you to control how your users manage federated cloud shares:

Your Apache Web server must have mod_rewrite enabled, and you must have trusted_domains correctly configured in config.php to allow external connections (see Installation wizard). Consider also enabling SSL to encrypt all traffic between your servers .

Your Nextcloud server creates the share link from the URL that you used to log into the server, so make sure that you log into your server using a URL that is accessible to your users. For example, if you log in via its LAN IP address, such as http://192.168.10.50, then your share URL will be something like http://192.168.10.50/nextcloud/index.php/s/jWfCfTVztGlWTJe, which is not accessible outside of your LAN. This also applies to using the server name; for access outside of your LAN you need to use a fully-qualified domain name such as http://myserver.example.com, rather than http://myserver.

Changing the display of federated shares

By default, federated shares are displayed in a separate section in the Nextcloud interface. It is possible to change this behavior and display them in the same section as internal shares. This can be controlled with a occ command:

occ config:app:set --value false --type boolean files_sharing show_federated_shares_as_internal

Set the value to true to display federated shares mixed with internal shares, or false to keep them in a separate section (default).

Uploading big files > 512MB

The default maximum file size for uploads is 512MB. You can increase this limit up to what your filesystem and operating system allows. There are certain hard limits that cannot be exceeded:

64-bit filesystems have much higher limits; consult the documentation for your filesystem.

提示

The Nextcloud sync client is not affected by these upload limits as it is uploading files in smaller chunks. See Client documentation for more information on configuration options.

System configuration

Configuring your Web server

提示

Nextcloud comes with its own nextcloud/.htaccess file. Because php-fpm can't read PHP settings in .htaccess these settings must be set in the nextcloud/.user.ini file.

Set the following two parameters inside the corresponding php.ini file (see the Loaded Configuration File section of PHP version and information to find your relevant php.ini files) :

php_value upload_max_filesize 16G
php_value post_max_size 16G

The upload_max_filesize and post_max_size settings may not apply to file uploads through WebDAV single file PUT requests or Chunked file uploads For those, PHP and webserver timeouts are the limiting factor on the upload size.

Adjust these values for your needs. If you see PHP timeouts in your logfiles, increase the timeout values, which are in seconds:

php_value max_input_time 3600
php_value max_execution_time 3600

The mod_reqtimeout Apache module could also stop large uploads from completing. If you're using this module and getting failed uploads of large files either disable it in your Apache config or raise the configured RequestReadTimeout timeouts.

There are also several other configuration options in your Web server config which could prevent the upload of larger files. Please see the manual of your Web server for how to configure those values correctly:

Apache

Apache with mod_fcgid

提示

If you are using Apache/2.4 with mod_fcgid, as of February/March 2016, FcgidMaxRequestInMem still needs to be significantly increased from its default value to avoid the occurrence of segmentation faults when uploading big files. This is not a regular setting but serves as a workaround for Apache with mod_fcgid bug #51747.

Setting FcgidMaxRequestInMem significantly higher than normal may no longer be necessary, once bug #51747 is fixed.

Apache with mod_proxy_fcgi

nginx

提示

Make sure that client_body_temp_path points to a partition with adequate space for your upload file size, and on the same partition as the upload_tmp_dir or tempdirectory (see below). For optimal performance, place these on a separate hard drive that is dedicated to swap and temp storage.

If your site is behind a nginx frontend (for example a loadbalancer):

By default, downloads will be limited to 1GB due to proxy_buffering and proxy_max_temp_file_size on the frontend.

Configuring PHP

If you don't want to use the Nextcloud .htaccess or .user.ini file, you may configure PHP instead. Make sure to comment out any lines .htaccess pertaining to upload size, if you entered any.

If you are running Nextcloud on a 32-bit system, any open_basedir directive in your php.ini file needs to be commented out.

Set the following two parameters inside php.ini, using your own desired file size values:

upload_max_filesize = 16G
post_max_size = 16G

Tell PHP which temp directory you want it to use:

upload_tmp_dir = /var/big_temp_file/

Output Buffering must be turned off in .htaccess or .user.ini or php.ini, or PHP will return memory-related errors:

Configuring Nextcloud

As an alternative to the upload_tmp_dir of PHP (e.g. if you don't have access to your php.ini) you can also configure a temporary location for uploaded files by using the tempdirectory setting in your config.php (See Configuration Parameters).

If you have configured the session_lifetime setting in your config.php (See Configuration Parameters) file then make sure it is not too low. This setting needs to be configured to at least the time (in seconds) that the longest upload will take. If unsure remove this completely from your configuration to reset it to the default shown in the config.sample.php.

Adjust chunk size on Nextcloud side

For upload performance improvements in environments with high upload bandwidth, the server's upload chunk size may be adjusted:

sudo -E -u www-data php occ config:system:set --type int --value 20971520 files.chunked_upload.max_size

Put in a value in bytes (in this example, 20MB). Set --value 0 for no chunking at all.

Default is 104857600 (100 MiB).

Large file upload on object storage

Chunked file uploads do have a larger space consumption on the temporary folder when processing those uploads on object storage as the individual chunks get downloaded from the storage and will be assembled to the actual file on the Nextcloud servers temporary directory. It is recommended to increase the size of your temp directory accordingly and also ensure that request timeouts are high enough for PHP, webservers or any load balancers involved.

提示

In more recent versions of Nextcloud Server, when uploading to S3 in Primary Storage mode, we use S3 MultipartUpload. This allows chunked upload streaming of the chunks directly to S3 so that the final MOVE request no longer needs to assemble the final file on the Nextcloud server. This requires your memcache.distributed to be set to use Redis (or Memcached), otherwise we fall back on the prior behavior which consumes space on the Nextcloud Server for file assembly (as described above).

Federated Cloud Sharing

If you are using Federated Cloud Sharing and want to share large files, you can increase the timeout values for requests to the federated servers. Therefore, you can set davstorage.request_timeout in your config.php. The default value is 30 seconds.

Providing default files

You may distribute a set of default files and folders to all users by placing them in directory that is readable by the webserver user. This allows you to overwrite the files that are shipped by default with Nextcloud in core/skeleton. That custom directory should then be configured in the config.php via the configuration option skeletondirectory (see Configuration Parameters). Leave empty to not copy any skeleton files.

These files will be copied only to new users after their initial login, and existing users will not see files that are added to this directory after their first login. The files in the skeleton directory are copied into the users data directories, so they may change and delete the files without affecting the originals.

This screenshot shows a set of photos in the skeleton directory.

Set of photos in the Nextcloud skeleton directory

They appear on the user's Nextcloud Files page just like any other files.

Nextcloud Files page showing default skeleton files visible after first login

提示

Overwriting the files in core/skeleton is not recommended, because those changes will be overwritten on the next update of the Nextcloud server.

Default file templates

The default path for user templates is at /Templates (translated in the user's language). If you need to override this path for all users, you can set

occ config:app:set core defaultTemplateDirectory --value="CustomPath"

This will only apply to new users.

提示

To create their own template directory, users should click the + New button and then + Create templates folder.

Configuring Object Storage as Primary Storage

Nextcloud allows to configure object storages like OpenStack Swift or Amazon Simple Storage Service (S3) or any compatible S3-implementation (e.g. Minio or Ceph Object Gateway) as primary storage replacing the default storage of files.

By default, files are stored in nextcloud/data or another directory configured in the config.php of your Nextcloud instance. This data directory might still be used for compatibility reasons)

Differences from External Storage

When an object store is used as Primary Storage, Nextcloud requires exclusive access over the bucket being used. All metadata (filenames, directory structures, etc) is stored in Nextcloud and not in the object store. The metadata is only stored in the database and the object store only holds the file content by unique identifier.

Performance Implications

Because of this, object stores configured as Primary Storage usually perform better than when using the same object store via the External Storage support application, but the downside is being unable to access the files from outside of Nextcloud. This makes using an object store as Primary Storage distinct from using an object store via External Storage.

Data Backup and Recovery Implications

One impact of using an object store as Primary Storage is that your data backup strategy needs to incorporate this. Your data is no longer stored on your Nextcloud server, but your files are also no longer accessible by simply bypassing your Nextcloud server and accessing your object store directly.

Configuration

Primary object stores need to be configured in config.php by specifying the objectstore backend and any backend specific configuration.

提示

Configuring a primary object store on an existing Nextcloud instance will make all existing files on the instance inaccessible.

The configuration has the following structure:

'objectstore' => [
    'class' => 'Object\\Storage\\Backend\\Class',
    'arguments' => [
        ...
    ],
],

OpenStack Swift

The OpenStack Swift backend mounts a container on an OpenStack Object Storage server into the virtual filesystem.

The class to be used is OCFilesObjectStoreSwift

Both openstack v2 and v3 authentication are supported,

V2 Authentication:

'objectstore' => [
    'class' => '\\OC\\Files\\ObjectStore\\Swift',
    'arguments' => [
        'username' => 'username',
        'password' => 'Secr3tPaSSWoRdt7',
        // the container to store the data in
        'bucket' => 'nextcloud',
        'autocreate' => true,
        'region' => 'RegionOne',
        // The Identity / Keystone endpoint
        'url' => 'http://example.com/v2.0',
        // optional on some swift implementations
        'tenantName' => 'username',
        'serviceName' => 'swift',
        // The Interface / url Type, optional
        'urlType' => 'internal'
    ],
],

V3 Authentication:

'objectstore' => [
    'class' => 'OC\\Files\\ObjectStore\\Swift',
    'arguments' => [
        'autocreate' => true,
        'user' => [
            'name' => 'UserName',
            'password' => 'Secr3tPaSSWoRdt7',
            'domain' => [
                'name' => 'Default',
            ],
        ],
        'scope' => [
            'project' => [
                'name' => 'TenantName',
                'domain' => [
                    'name' => 'Default',
                ],
            ],
        ],
        'serviceName' => 'swift',
        'region' => 'regionOne',
        'url' => 'http://example.com/v3',
        'bucket' => 'nextcloud',
    ],
],

Simple Storage Service (S3)

The Simple Storage Service (S3) backend mounts a bucket on an Amazon S3 object storage or compatible implementation (e.g. Minio or Ceph Object Gateway) into the virtual filesystem.

The class to be used is OCFilesObjectStoreS3

Amazon-hosted S3:

'objectstore' => [
    'class' => '\\OC\\Files\\ObjectStore\\S3',
    'arguments' => [
        'bucket' => 'my-nextcloud-store',
        'region' => 'us-east-1',
        'key' => 'EJ39ITYZEUH5BGWDRUFY',
        'secret' => 'M5MrXTRjkyMaxXPe2FRXMTfTfbKEnZCu+7uRTVSj',
    ],
],

Non-Amazon hosted S3:

'objectstore' => [
    'class' => '\\OC\\Files\\ObjectStore\\S3',
    'arguments' => [
        'bucket' => 'my-nextcloud-store',
        'hostname' => 's3.example.com',
        'key' => 'EJ39ITYZEUH5BGWDRUFY',
        'secret' => 'M5MrXTRjkyMaxXPe2FRXMTfTfbKEnZCu+7uRTVSj',
        'port' => 8443,
        // required for some non-Amazon S3 implementations
        'use_path_style' => true,
    ],
],

Minimum required parameters are:

提示

You will probably need to specify additional parameters beyond these, unless the default values (see below) exactly match your situation. In particular, your region (if Amazon hosted) or hostname (if non-Amazon hosted).

Optional parameters most commonly needing adjustment (and their defaults values if left unconfigured):

Optional parameters sometimes needing adjustment:

Optional parameters less commonly needing adjustment:

If you are using Amazon S3: the region parameter is required unless you're happy with the default of eu-west-1. There is no need to override the hostname or port. And storageClass only needs to be modified if you're using a different configuration at AWS. Lastly, use_path_style is rarely required with Amazon, but some legacy Amazon datacenters may require it.

If you using a non-Amazon hosted S3 store: you will need to set the hostname parameter (and can ignore the region parameter). You may need to use use_path_style if your non-Amazon S3 store does not support requests like https://bucket.hostname.domain/. Setting use_path_style to true configures the S3 client to make requests like https://hostname.domain/bucket instead.

Microsoft Azure Blob Storage

The Azure Blob Storage backend mounts a container on Microsoft's Azure Blob Storage into the virtual filesystem.

The class to be used is OCFilesObjectStoreAzure

'objectstore' => [
    'class' => '\\OC\\Files\\ObjectStore\\Azure',
    'arguments' => [
        'container' => 'nextcloud',
        'autocreate' => true,
        'account_name' => 'account_name',
        'account_key' => 'xxxxxxxxxx'
    ],
],

Multibucket Object Store

It's possible to configure Nextcloud to distribute the data over multiple buckets for scalability purposes.

To setup multiple buckets, set 'multibucket => true' in the object store configuration in config.php:

'objectstore' => [
    'class' => 'Object\\Storage\\Backend\\Class',
    'arguments' => [
        'multibucket' => true,
        // optional, defaults to 64
        'num_buckets' => 64,
        // will be postfixed by an integer in the range from 0 to (num_nuckets-1)
        'bucket' => 'nextcloud_',
        ...
    ],
],

Multibucket object store backend maps every user to a range of buckets and saves all files for that user in their corresponding bucket.

提示

While it is possible to change the number of buckets used by an existing Nextcloud instance, the user-to-buckets mapping is only created once, so only newly created users will be mapped to the updated range of buckets.

You can find out more information about upscaling with object storage and Nextcloud in the Nextcloud customer portal.

Multibucket Object Store with per Bucket configuration overrides

When using an Object Store with 'multibucket => true' it is possible to configure overrides for all config options per bucket:

'objectstore' => [
    'class' => 'Object\\Storage\\Backend\\Class',
    'arguments' => [
        'multibucket' => true,
        'bucket' => 'nextcloud_',
        'perBucket' => [
            'nextcloud_1' => [
                'port' => 9999,
            ],
        ],
    ],
],

This can be useful for example if you want to configure credentials per bucket that is used by a Team folder. A script for provisioning new Team folders this way could look like this (first make sure the bucket exists with those credentials):

occ config:system:set --type=string --value=KEYVALUE objectstore arguments perBucket BUCKETNAME key
occ config:system:set --type=string --value=SECRETVALUE objectstore arguments perBucket BUCKETNAME secret
occ groupfolders:create --bucket BUCKETNAME TEAMFOLDERNAME

The credentials must be set before the new Team folder is created.

Multi-instance Object Store

It's possible to configure Nextcloud to distribute the data over multiple object store instances for further scaling and gradual migration.

To setup multiple buckets, set 'objectstore' to an array of named configurations configuration in config.php and set the 'default' to the name of the configuration to use for newly created users:

'objectstore' => [
    'default' => 'server2',
    'root' => 'server1',
    'server1' => [
        'class' => 'Object\\Storage\\Backend\\Class',
        'arguments' => [
            'hostname' => 's3-server1.example.com',
            'bucket' => 's1_nextcloud',
            ...
        ],
    ],
    'server2' => [
    'class' => 'Object\\Storage\\Backend\\Class',
        'arguments' => [
            'multibucket' => true,
            'hostname' => 's3-server2.example.com',
            'bucket' => 's2_nextcloud_',
            ...
        ],
    ],
],

提示

Bucket names must be unique between all configured object store instances.

Newly created users will be mapped to the object store instance set in default. Files that are not part of the users storage are put in the root instance, or in the default instance if no root instance is configured.

In the above example, if server2 is starting to run low on capacity, an admin can setup and configure a new server3 and change the default to server3. Than any newly created user will have their files put on server3.

提示

As with multibucket object store, the user-to-instance mapping is only created once, so only newly created users will be mapped to the new default instance.

It is possible to mix different object store backends and multibucket and non-multibucket in a multi-instance configuration.

S3 SSE-C encryption support

Nextcloud supports server side encryption, also known as SSE-C, with compatible S3 bucket provider. The encryption and decryption happens on the S3 bucket side with a key provided by the Nextcloud server.

The key can be specified with the sse_c_key parameter which needs to be provided as a base64 encoded string with a maximum length of 32 bytes. A random key could be generated using the the following command:

openssl rand 32 | base64

The following example shows how to configure the S3 object store with SSE-C encryption support in the objectstore section of the Nextcloud config.php file:

'objectstore' => [
    array (
        'class' => 'OC\\Files\\ObjectStore\\S3',
        'arguments' =>
        array (
            'bucket' => 'nextcloud',
            'key' => 'nextcloud',
            'secret' => 'nextcloud',
            'hostname' => 's3',
            'port' => '443',
            'use_ssl' => true,
            'use_path_style' => true,
            'autocreate' => true,
            'verify_bucket_exists' => true,
            'sse_c_key' => 'o9d3Q9tHcPMv6TIpH53MSXaUmY91YheZRwuIhwCFRSs=',
        ),
    );
],

External Storage

The External Storage Support application enables you to mount external storage services and devices as secondary Nextcloud storage devices. You may also allow users to mount their own external storage services.

Enabling

External Storage Support is provided by a bundled (automatically installed) app. It is disabled by default, so to use this feature you simply need to enable it under Apps.

Enable external storage on your Apps page.

Configuring

To access the settings for configuring external storage mounts, click your Profile icon and select Settings from the dropdown. On the left side, under Administration, select External Storage.

提示

External storage can also be configured via the occ command. See occ documentation.

To create a new external storage mount, select an available backend from the Add storage dropdown. Each backend has different required options, which are configured in the configuration fields.

Each backend may also accept multiple authentication methods. These are selected with the dropdown under Authentication. Different backends support different authentication mechanisms; some are specific to the backend, while others are more generic. See External Storage authentication mechanisms for more detailed information.

When you select an authentication mechanism, the configuration fields change as appropriate for the chosen mechanism. For example, the SFTP backend supports Username and password, Log-in credentials, save in session, and RSA public key.

An SFTP configuration example.

Required fields are marked with a red border. When all required fields are filled, the storage is automatically saved. A green dot next to the storage row indicates the storage is ready for use. A red or yellow icon indicates that Nextcloud could not connect to the external storage, so you need to re-check your configuration and network availability.

If there is an error on the storage, it will be marked as unavailable for ten minutes. To re-check it, click the colored icon or reload your Admin page.

Folder name

The Folder name is the name the folder will have within Nextcloud - the name that will be visible to NextCloud users.

Note that the folder name cannot include a path or subdirectory - do not include slashes in your Folder name.

Usage of variables for mount paths

The external storage mounting mechanism accepts variables in the mount path.

Use $user for automatic substitution with the logged-in user's username.

Use $home for automatic substitution with a configurable home directory variable (requires LDAP; see Special attributes in the LDAP configuration documentation for details).

In the following example, the mount point for a logged-in user "alice" would resolve to /opt/userDirectories/alice/myPictures.

External storage user variable substitution

User and Group Permissions

A storage configured in a user's personal settings is available only to the user who created it. A storage configured in the Admin settings is available to all users by default, but it can be restricted to specific users and groups in the Available for field.

User and groups selector

Mount Options

The overflow menu (three dots) exposes the settings and trashcan icons. Click the trashcan to delete the mount point. The settings button allows you to configure each storage mount individually with the following options:

The Encryption checkbox is visible only when the Encryption app is enabled. Note that server-side encryption is not available for other Nextcloud servers used as external storage.

Enable Sharing allows the Nextcloud admin to enable or disable sharing on individual mount points. When sharing is disabled, the shares are retained internally so that you can re-enable sharing and the previous shares become available again. Sharing is disabled by default.

Additional mount options exposed on mouseover.

Using Self-Signed Certificates

When using self-signed certificates for external storage mounts, the certificate must be imported into the personal settings of the user. Please refer to Nextcloud HTTPS External Mount for more information.

Available Storage Backends

The following backends are provided by the external storages app.

提示

A non-blocking or correctly configured SELinux setup is needed for these backends to work. Please refer to SELinux configuration.

Allow Users to Mount External Storage

Check Enable User External Storage to allow your users to mount their own external storage services, and check the backends you want to allow. Beware, as this allows a user to make potentially arbitrary connections to other services on your network!

Checkboxes to allow users to mount external storage services.

Detecting changes made outside Nextcloud

When files are added, modified, or deleted on an external storage directly (without going through Nextcloud), Nextcloud will not know about those changes immediately. Nextcloud maintains an internal index (the filecache) that is only updated when Nextcloud itself performs a scan. Until that scan happens, the filecache is stale and the changes are invisible to Nextcloud, desktop clients, and mobile apps.

How the "Filesystem check frequency" option works

The Filesystem check frequency mount option (see Mount Options) controls what happens when a WebDAV PROPFIND request reaches the Nextcloud server for a path inside the external storage:

This option is only about the server's behavior during a PROPFIND. It does not trigger any background polling and does not change how desktop clients or mobile apps behave.

Because this rescan is driven by user actions (opening a folder in the web UI, browsing in the mobile app, or a client issuing a PROPFIND), change detection remains random and unreliable for deep folder hierarchies.

Why desktop clients miss deep changes

The desktop sync client only issues a PROPFIND on the root of the sync folder on every sync cycle because scanning the entire tree would be too expensive. It relies on etag propagation: when a file changes, the etag of every parent folder up to the root must also change, giving the client a trail to follow down to the changed file.

When a change is made outside Nextcloud, no etag is updated. The client sees no trail from the root and never follows it down to the changed file.

How to make external changes reliably detectable

There are two approaches, depending on the storage type:

A) SMB/CIFS storages — use update notifications

The files_external:notify command listens for change events sent by the SMB server itself. When a change event arrives, Nextcloud rescans the affected path and propagates the etag changes up to the root, so desktop clients pick up the change on their next sync cycle.

occ files_external:notify <mount_id>

See SMB/CIFS for setup details, including authentication requirements and how to reduce sync delay.

B) All other storages — periodic rescan via cron

For storage types that do not support push notifications, set up a cron job that rescans the external storage periodically using its mount ID:

sudo -E -u www-data php occ files_external:scan <mount_id>

You can find the mount ID with occ files_external:list. See Using the occ command for the full files_external:scan reference. A typical interval is every 15 minutes; adjust to balance freshness against server load.

提示

If you are running Nextcloud AIO, the equivalent command is:

sudo docker exec --user www-data -i nextcloud-aio-nextcloud php occ files_external:scan <mount_id>

Limitation: renames are not detected reliably

Whenever Nextcloud rescans an external storage — whether via periodic cron (option B) or via the Once per direct access filesystem check frequency setting — the scanner cannot reliably detect that an entry was renamed. It sees the old name as deleted and the new name as a newly created entry. This causes metadata loss: all shares, tags, comments, and activity history associated with the old entry are permanently deleted from Nextcloud's database.

注意

If users rename files or folders directly on the external storage (outside Nextcloud), that metadata loss is unavoidable. To preserve metadata, all renames should be done through Nextcloud itself, or — for SMB — use update notifications (option A) which handles renames via the SMB change event stream.

Troubleshooting File Name Encoding

When using external storage, it can happen that some files with special characters will not appear in the file listing, or they will appear but not be accessible.

When this happens, please run the files scanner, for example:

sudo -E -u www-data php occ files:scan --all

If the scanner reports an encoding issue on the affected file, please enable Mac encoding compatibility in the mount options and then rescan the external storage.

提示

This mode comes with a performance impact because Nextcloud will always try both encodings when detecting files on external storages.

Mac computers use the NFD Unicode normalization for file names, which is different from NFC, the one used by other operating systems. Mac users might upload files directly to the external storage using NFD-normalized file names. When uploading through Nextcloud, file names will always be normalized to the NFC standard for consistency.

It is recommended to let Nextcloud use external storages exclusively to avoid such issues.

See also the technical explanation about NFC vs NFD normalizations.

Amazon S3

To connect an Amazon S3 (or compatible) bucket to Nextcloud you will need to know your:

注意

Some S3-compatible storages, including Amazon S3, allow repeating delimiters / (e.g. Photos//cat.png). This is unsupported and prefixes with repeating delimiters and its contents are ignored.

In the Folder name field enter a folder name to use as the local mountpoint for this external storage. If this does not exist it will be created.

In the External storage field select Amazon S3.

In the Authentication field select Access key.

In the Bucket field enter your S3 bucket name. [Note: Even if non-Amazon hosted, bucket names must meet AWS S3 naming requirements regardless of what your S3 provider/platform considers acceptable - i.e. no underscores]

In the Access key field enter your S3 access key ID.

In the Secret key field enter your S3 access key.

If you are using Amazon S3: the Region parameter is required unless you're happy with the default of eu-west-1 (which will be used if you don't specify anything). There is no need to override the Hostname or Port. And Storage Class only needs to be modified if you're using a different configuration at AWS. Lastly, Enable Path Style is rarely required with Amazon, but some legacy Amazon datacenters may require it. Leave Legacy (v2) authentication unselected.

If you using a non-Amazon hosted S3 store: you will need to set the Hostname parameter (and can ignore the Region parameter). You may need to enable Enable Path Style if your non-Amazon S3 store does not support requests like https://bucket.hostname.domain/. Setting Enable Path Style to true configures the S3 client to make requests like https://hostname.domain/bucket instead. It's rare to need Legacy (v2) authentication, but enable it if your in-house object store or service provider requires it over the default (v4) authentication.

In the Available for field enter the users or groups who you want to give give access to your S3 mount.

The Enable SSL checkbox enables HTTPS connections and generally preferred. It is the default unless you disable it here.

Optionally, a 32-byte base64 encoded SSE-C key can be provided for server side encryption. See Configuring Object Storage as Primary Storage and the SSE-C AWS documentation for more information how to generate a key.

See External Storage for additional mount options and information.

See External Storage authentication mechanisms for more information on authentication schemes.

FTP/FTPS

To connect to an FTP server, you will need:

Your new mountpoint is available to all users by default, and you may restrict access by entering specific users or groups in the Available for field.

Optionally, Nextcloud can use FTPS (FTP over SSL) by checking Secure ftps://. This requires additional configuration with your root certificate if the FTP server uses a self-signed certificate.

Nextcloud GUI FTP configuration.

提示

The external storage FTP/FTPS needs the allow_url_fopen PHP setting to be set to 1. When having connection problems make sure that it is not set to 0 in your php.ini. See PHP version and information to learn how to find the right php.ini file to edit.

See External Storage for additional mount options and information.

FTP uses the password authentication scheme; see External Storage authentication mechanisms for more information on authentication schemes.

Local

Local storages provide access to any directory on the Nextcloud server. Since this is a significant security risk, Local storage can only be configured in the Nextcloud admin settings. Non-admin users cannot create Local storage mounts.

Use this to mount any directory on your Nextcloud server that is outside of your Nextcloud data/ directory. This directory must be readable and writable by your HTTP server user. These ownership and permission examples are on Ubuntu Linux:

sudo chown -R www-data:www-data /path/to/localdir
sudo chmod -R 0750 /path/to/localdir

Important: If you use consecutive commands, make sure, you are user www-data:

sudo -E -u www-data bash
cd /path/to/localdir
mkdir data

In the Folder name field enter the folder name that you want to appear on your Nextcloud Files page.

In the Configuration field enter the full filepath of the directory you want to mount.

In the Available for field enter the users or groups who have permission to access the mount. By default all users have access.

See External Storage for additional mount options and information.

See External Storage authentication mechanisms for more information on authentication schemes.

Nextcloud

A Nextcloud storage is a specialized WebDAV storage, with optimizations for Nextcloud-Nextcloud communication. See the WebDAV documentation to learn how to configure a Nextcloud external storage.

When filling in the URL field, use the path to the root of the Nextcloud installation, rather than the path to the WebDAV endpoint. So, for a server at https://example.com/nextcloud, use https://example.com/nextcloud and not https://example.com/nextcloud/remote.php/dav.

See External Storage for additional mount options and information.

See External Storage authentication mechanisms for more information on authentication schemes.

OpenStack Object Storage

OpenStack Object Storage is used to connect to an OpenStack Swift server, or to Rackspace. Two authentication mechanisms are available: one is the generic OpenStack mechanism, and the other is used exclusively for Rackspace, a provider of object storage that uses the OpenStack Swift protocol.

The OpenStack authentication mechanism uses the OpenStack Keystone v2 protocol. Your Nextcloud configuration needs:

OpenStack configuration.

The Rackspace authentication mechanism requires:

You must also enter the term cloudFiles in the Service name field.

OpenStack configuration.

It may be necessary to specify a Region. Your region should be named in your account information, and you can read about Rackspace regions at About Regions.

The timeout of HTTP requests is set in the Request timeout field, in seconds.

See External Storage for additional mount options and information.

See External Storage authentication mechanisms for more information on authentication schemes.

SFTP

Nextcloud's SFTP (SSH File Transfer Protocol) backend supports both password and public key authentication.

The Host field is required. The default port is 22 (SSH).

For public key authentication, you can generate a public/private key pair from your SFTP with secret key login configuration.

Generating an RSA key pair in the SFTP configuration.

After generating your keys, you need to copy your new public key to the destination server to .ssh/authorized_keys. Nextcloud will then use its private key to authenticate to the SFTP server.

The default Remote Subfolder is the root directory (/) of the remote SFTP server, and you may enter any directory you wish.

See External Storage for additional mount options and information.

See External Storage authentication mechanisms for more information on authentication schemes.

SMB/CIFS

Nextcloud can connect to Windows file servers or other SMB-compatible servers with the SMB/CIFS backend.

提示

The SMB/CIFS backend requires smbclient or the PHP smbclient module (php-smbclient / libsmbclient-php) to be installed on the Nextcloud server. The PHP smbclient module is strongly preferred — without it, the backend falls back to spawning the smbclient binary, which has known limitations (notably, downloads of files larger than ~512 MB from external SMB shares can fail; see nextcloud/server#31308). These should be included in any Linux distribution. (See PECL smbclient if your distro does not include them.)

You need the following information:

Optionally, you can specify a Domain. This is useful in cases where the SMB server requires a domain and a username, and an advanced authentication mechanism like session credentials is used so that the username cannot be modified. This is concatenated with the username, so the backend gets domain\username

提示

For improved reliability and performance, we recommended installing libsmbclient-php, a native PHP module for connecting to SMB servers.

Samba external storage configuration.

See External Storage for additional mount options and information.

See External Storage authentication mechanisms for more information on authentication schemes.

Case sensitive file system

This option tells Nextcloud whether the SMB share is backed by a case-sensitive filesystem. It does not change how the SMB server stores files, it only affects how Nextcloud performs lookups and validates paths.

If the setting does not match the SMB server's filesystem, you can run into confusing behavior:

SMB update notifications

另见

Detecting changes made outside Nextcloud explains why external changes to a mounted storage are not detected automatically and how update notifications fit into that picture.

Nextcloud can use smb update notifications to listen for changes made to a configured SMB/CIFS storage and detect external changes made to the storage in near real-time.

提示

Due to limitations of linux based SMB servers, this feature only works reliably on Windows SMB servers.

提示

Using update notifications requires smbclient 4.x or newer. Due to limitations with the smbclient PHP module, the smbclient binary is required even when using the PHP module.

To start listening to update notifications, start the occ command like this:

occ files_external:notify <mount_id>

You can find the mount id for a specific storage using occ files_external:list

On default this command shows no output, can you see the list of detected changes by passing the -v option to the command.

SMB authentication

Update notifications are not supported when using 'Login credentials, save in session' authentication. Using update notifications is only supported with 'Login credentials, save in database'.

Even when using 'Login credentials, save in database' or 'User entered, stored in database' authentication the notify process can not use the credentials saved to attach to the smb shares because the notify process does not run in the context of a specific user in those cases you can provide the username and password using the --username and --password arguments.

Decrease sync delay

Any updates detected by the notify command will only be synced to the client after the Nextcloud cron job has been executed (usually every 15 minutes). If this interval is too high for your use case, you can decrease it by running occ files:scan --unscanned --all at the desired interval. Note that this might increase the server load and you'll need to ensure that there is no overlap between runs.

Hidden files upload failure or not shown

If you have the configuration hide dot files = Yes, you will not be able to upload a hidden file (dot file) nor will you be able to show hidden files on your filelist (even if the 'show hidden file' option is checked on the nextcloud settings. Make sure you have the following option in your configuration: hide dot files = No

WebDAV

Use this backend to mount a directory from any WebDAV server, or another Nextcloud server.

You need the following information:

Optionally, a Remote Subfolder can be specified to change the destination directory. The default is to use the whole root.

Webdav configuration form.

提示

CPanel users should install Web Disk to enable WebDAV functionality.

See External Storage for additional mount options and information.

See External Storage authentication mechanisms for more information on authentication schemes.

External Storage authentication mechanisms

Nextcloud storage backends accept one or more authentication schemes such as passwords, OAuth, or token-based, to name a few examples. Each authentication scheme may be implemented by combining multiple authentication mechanisms. Different mechanisms require different configuration parameters, depending on their behavior.

Authentication types

Special mechanisms

The None authentication mechanism requires no configuration parameters, and is used when a backend requires no authentication.

The Built-in authentication mechanism itself requires no configuration parameters, but is used as a placeholder for legacy storages that have not been migrated to the new system and do not take advantage of generic authentication mechanisms. The authentication parameters are provided directly by the backend.

Password-based mechanisms

The Username and password mechanism requires a manually-defined username and password. These get passed directly to the backend and are specified during the setup of the mount point.

The Log-in credentials, save in session mechanism uses the Nextcloud login credentials of the user to connect to the storage. These are not stored anywhere on the server, but rather in the user session, giving increased security. This method has some important drawbacks, since Nextcloud has no access to the storage credentials and therefore cannot perform any background tasks on the storage:

The Log-in credentials, save in database mechanism uses the Nextcloud login credentials of the user to connect to the storage. These are stored in the database encrypted with the shared secret. This allows to share files from within this mount point.

The User entered, store in database mechanism work in the same way as the "Username and password" mechanism but the credentials need to be specified by each user individually. Before the first access to that mount point the user will be prompted to enter the credentials.

The Global credentials mechanism uses the general input field for "Global credentials" in the external storage settings section as source for the credentials instead of individual credentials for a mount point.

Considerations for shared storage

Public-key mechanisms

Currently only the RSA mechanism is implemented, where a public/private keypair is generated by Nextcloud and the public half shown in the GUI. The keys are generated in the SSH format, and are currently 1024 bits in length. Keys can be regenerated with a button in the GUI.

After generating your keys, you need to copy your new public key to the destination server to .ssh/authorized_keys.

See SFTP for additional information on how to set up certificate based authentication on SFTP.

Form on admin page for generating RSA keys.

Considerations for shared storage

Every external storage, which is using user specific authentication, is connected individually. Nextcloud cannot recognise shared file locks across individual connections, even when accessing the same file.

This has an influence on e.g. file locking as a locked individual file is not shown as locked to other users or users cannot collaboratively edit documents.

If collaborative working on external storage is required, the authentication "Global credentials" has to be used.

Server-side Encryption

Overview

Nextcloud provides several encryption methods to protect your data. These work at different layers of the system and address different security needs. This guide focuses on Nextcloud's built-in Server-Side Encryption (SSE).

提示

Encryption and risk management is a complex and nuanced topic. Unless you are already an expert, it is recommended to consult a professional or perform a deep dive to ensure your approach targets your specific concerns. You may also find this Nextcloud Blog post helpful: Data encryption methods in Nextcloud. It provides a solid high-level overview of the different approaches commonly considered when using Nextcloud.

Definitions

Encryption Method Comparison

Method Encryption Location Who Can Decrypt? Protects Against
SSE (Master Key) Server Admins & users External storage providers
SSE (User Keys) Server Users & malicious admins External storage providers
SSE (User Keys w/ Recovery) Server Users & admins with recovery key External storage providers
E2EE Client Users only Admins, external storage providers
Disk/Block Encryption Server OS admin Physical tampering, theft

Key Points & Limitations

注意

SSE does not encrypt filenames or folder structures, only file contents.

提示

Don't confuse Nextcloud's SSE with S3 SSE-C (also supported).

Changed in version 9.0.0: Nextcloud (since v9.0.0) supports Authenticated Encryption for all newly encrypted files. See https://hackerone.com/reports/108082 for technical details.

提示

For maximum security, configure external storage with "Check for changes: Never". This causes Nextcloud to ignore new files not added via Nextcloud, preventing unauthorized additions by external storage admins. Do not use this if your storage is subject to legitimate external changes.

Before You Enable Encryption

  1. Read this guide fully and understand the risks.
  2. Back up your instance configuration and all encryption keys in a safe location before proceeding.
  3. Decide which key management mode suits your needs (see below).

Key Management Modes

Master Key (default):

User Keys:

How to choose:

To select user key mode:

Run:

occ encryption:disable-master-key

before enabling encryption.

Enabling Encryption (Step-by-Step)

  1. Go to the Server-side encryption section of your Admin page.
  2. Check Enable server-side encryption.
  3. You’ll see a message: "No encryption module loaded." Go to your Apps page and enable the Nextcloud Default Encryption Module.
  4. Return to your Admin page. The module will appear and be auto-selected.
  5. Log out and log back in to initialize your encryption keys.
  6. Optional: Un-check the box for encrypting home storage if you wish to keep local files unencrypted.

Backups

Encryption keys are stored in:

Encrypting External Mountpoints and Team Folders

occ config:app:set groupfolders enable_encryption --value=true

提示

Only new or updated files in team folders will be encrypted.

Managing Encryption via occ Commands

Here is a reference table for common occ commands:

Command Description
occ encryption:status Show encryption status and module
occ encryption:enable Enable server-side encryption
occ encryption:list-modules List available encryption modules
occ encryption:set-default-module [Module ID] Select default encryption module
occ encryption:encrypt-all Encrypt all files for all users
occ encryption:decrypt-all [user] Decrypt all files (or for one user)
occ encryption:show-key-storage-root Show key storage location
occ encryption:change-key-storage-root [dir] Move key storage directory
occ encryption:enable-master-key Enable master key mode
occ encryption:disable-master-key Disable master key mode
occ encryption:fix-encrypted-version Fix bad signature errors
occ encryption:fix-key-location [user] Fix key not found errors

提示

See the Encryption commands section of the occ reference guide for further encryption command examples and details.

Example: Move keys to a new directory (Ubuntu Linux):

cd /your/nextcloud/data
mkdir keys
chown -R root:www-data keys
chmod -R 0770 keys
occ encryption:change-key-storage-root keys

Encrypting All Files

By default, only new and changed files are encrypted when you enable SSE. To encrypt all files for all users run:

occ encryption:encrypt-all

Decrypting Files / Disabling Encryption

occ encryption:decrypt-all

You can decrypt for individual users:

occ encryption:decrypt-all <user-id>

Data Not Encrypted

Only file contents are encrypted. The following are not encrypted:

Not Encrypted
Filenames and folder structures
Existing trash bin files
Existing historical file versions
Image thumbnails
Image previews
Full text search index
Application data that isn't file-based (e.g., Deck, Tables)

User Keys: Sharing & Recovery

Sharing encrypted files:

Enabling file recovery keys:

Recovery keys are only available in per-user key mode (not the default master key mode).

注意

The recovery process can be slow and resource-intensive, especially for instances with large amounts of encrypted data. Test recovery procedures before relying on them in production.

LDAP and External User Backends

Troubleshooting

Why don't I see the recovery key option in the Encryption settings?

Recovery keys are only available in per-user key mode. Since Nextcloud 13, the default encryption mode uses master keys (system-wide encryption). Master key mode does not expose recovery key options in the Admin settings because recovery keys are not needed—admins can reset user passwords and files remain accessible.

If you are using master key mode (the default and recommended mode), you do not need recovery keys. Recovery keys are only relevant for per-user key setups, which are maintained for compatibility with older deployments.

See Key Management Modes for guidance on the differences between master key and per-user key modes, and GitHub Issue #8283 for technical context on this design decision.

Invalid private key for encryption app

See GitHub Issue #8546 and workaround.

Bad signature error

In some rare cases, encrypted files cannot be downloaded and return a "500 Internal Server Error." If the Nextcloud log contains an error about "Bad Signature," run the following command to repair affected files:

occ encryption:fix-encrypted-version userId --path=/path/to/broken/file.txt

Replace "userId" and the path accordingly. The command will perform a test decryption for all files and automatically repair those with a signature error.

Encryption key cannot be found

If the logs contain an error stating that the encryption key cannot be found, you can manually search the data directory for a folder that has the same name as the file name. For example, if a file "example.md" cannot be decrypted, run:

find path/to/datadir -name example.md -type d

Then check the results located in the files_encryption folder. If the key folder is in the wrong location, move it to the correct folder and try again.

The data/files_encryption folder contains encryption keys for group folders and system-wide external storages, while data/$userid/files_encryption contains the keys for specific user storage files.

提示

This can happen if encryption was disabled at some point but the occ command for decrypt-all was not run. If someone then moved the files to another location, the keys did not get moved.

Encryption key cannot be found with external storage or group folders

To resolve this issue, run the following command:

sudo -E -u www-data php occ encryption:fix-key-location <user-id>

This will attempt to recover keys that were not moved properly.

If this doesn't resolve the problem, refer to the section Encryption key cannot be found for a manual procedure.

提示

There were two known issues where:

Further Reading

Server-side encryption details

This document describes the server-side encryption scheme implemented by Nextcloud's default encryption module. This includes:

These conventions apply throughout this document:

提示

However, files that have been encrypted in Nextcloud versions 15 and lower may have slightly different structures.

Key type: master key

This is the default encryption mode in Nextcloud. With master key encryption enabled there is one central key that is used to secure the files handled by Nextcloud. The master key is protected by the instance secret that is generated at installation time. The advantage of the master key encryption is that the encryption is transparent to the users but has the disadvantage that the server administrator is able to decrypt user files without knowing any user password.

Key type: public sharing key

The public sharing key is used to secure files that have been publicly shared. The advantage of the public sharing key is that it is independent of the selected encryption mode so that Nextcloud is able to provide publicly shared files to outside parties.

Key type: recovery key

The recovery key is used to provide a restore mechanism in cases where the user key encryption is enabled, where the administrator has enabled the recovery key feature and the user has opted into using the recovery key feature. The recovery key can then be used to restore files when users have lost their passwords. The recovery key is protected by a recovery password that the server administrator should store securely. The advantage of the recovery key is that files can be recovered but has the disadvantage that the server administrator is able to decrypt user files without knowing any user password.

Key type: user key

User key encryption needs to be explicitly activated by calling ./occ encryption:disable-master-key. In older versions of Nextcloud this had been enabled by default. With user key encryption enabled all users have their own user keys that are used to secure the files handled by Nextcloud. The user keys are protected by the user passwords. The advantage is that the server administrator is not able to decrypt user files without knowing any user password - unless the file is publicly shared or a recovery key is defined - but has the disadvantage that files are permanently lost if the users forget their user passwords - unless the files are (publicly) shared or a recovery key is defined.

提示

This method cannot be used with SAML authentication, because Nextcloud does not get a hold of any credentials whatsoever and therefore cannot use any users' passwords for encryption.

File type: public key file

Public key files contain RSA public keys that are used to encrypt/seal the share key files.

File format

Public key files are stored in PEM format.

File locations

The locations of public key files depend on their key type:

File type: private key file

Private key files contain RSA private keys that are used to decrypt/unseal the share key files. The RSA private key is encrypted and signed with a password and stored in a format that is specific to the Nextcloud encryption module.

File format

The RSA private key that is represented in PEM format is encrypted and Base64 encoded (denoted as $encryption). For the encryption an initialization vector of 16 bytes is selected (denoted as $iv). Furthermore a hexadecimally encoded message authentication code of 64 bytes is calculated (denoted as $signature). The resulting file contains:

"HBEGIN:cipher:AES-256-CTR:keyFormat:hash:HEND".
$encrypted."00iv00".$iv."00sig00".$signature."xxx"

File locations

The locations of private key files depend on their key type:

File type: share key file

Share key files contain so-called envelope keys that are needed to decrypt the file key files. The envelope keys are created by openssl_seal() during the encryption and are needed for openssl_open() during the decryption. The envelope keys are encrypted with the public keys of the recipients that are allowed to read the actual files.

File format

The envelope keys are stored in binary format.

File locations

The locations of share key files depend on the type of the encrypted file:

File type: file key file

File key files contain symmetric keys used to encrypt the actual files. The file keys consist of 32 random bytes and are encrypted/sealed with the envelope keys stored in the share key files.

File format

The file keys are stored in binary format.

File locations

The locations of the file key files depend on the type of the encrypted file:

File type: file

Files contain the actual file content. The file content is encrypted and signed with a password and stored in a format that is specific to the Nextcloud encryption module.

File format

The file content is split into blocks of 6072 bytes. Each block is encrypted and Base64 encoded (denoted as $encryption[0..$n]). For the encryption an initialization vector of 16 bytes is selected for each block (denoted as $iv[0..$n]). Furthermore a hexadecimally encoded message authentication code of 64 bytes is calculated of each block (denoted as $signature[0..$n]). An encrypted block has a total size of 8192 bytes (8096 bytes for $encrypted[], 6 bytes for "00iv00", 16 bytes for $iv[], 7 bytes for "00sig00", 64 bytes for $signature[] and 3 bytes for "xxx"). Only the last encrypted block may be shorter. The header of the encrypted file is padded with 8147 bytes of "-" (denoted as $padding) to a total of 8192 bytes. The resulting file contains:

"HBEGIN:cipher:AES-256-CTR:keyFormat:hash:HEND".$padding.
$encrypted[0]."00iv00".$iv[0]."00sig00".$signature[0]."xxx".
$encrypted[1]."00iv00".$iv[1]."00sig00".$signature[1]."xxx".
$encrypted[2]."00iv00".$iv[2]."00sig00".$signature[2]."xxx".
[...]
$encrypted[$n]."00iv00".$iv[$n]."00sig00".$signature[$n]."xxx"

File locations

The locations of the files depend on the type of the encrypted file:

Key generation: generate the key pair

The key pair has to be generated with the openssl_pkey_new() function. Then the private key and public key are extracted from the the key resource with the openssl_pkey_export() function.

Key generation: store the public key

The public key is written to the $username.".publicKey" file as documented in File type: public key file.

Key generation: store the private key

Derive the encryption key

The salt for the encryption key is derived by creating a raw SHA256 hash of $uid.$instanceId.$instanceSecret with the hash() function. $instanceId can be retrieved as instanceid from the config.php. $instanceSecret can be retrieved as secret from the config.php.

The encryption key is then derived by creating a raw SHA256-PBKDF2 hash of the password with the salt, 100.000 rounds and (by default) with a target size of 32 bytes (as required for AES-256-CTR) with the hash_hmac() function (denoted as $passphrase).

The used password depends on the key type:

Encrypt the private key

The initialization vector is generated as a random string of 16 bytes with the random_bytes() function (denoted as $iv). The private key is (by default) AES-256-CTR encrypted with the $iv and the $passphrase with the openssl_encrypt() function and returned as Base64 encoded without zero-padding (denoted as $encrypted).

Sign the private key

The message authentication key is derived by creating a raw SHA512 hash of $passphrase.$version.$position."a" with the hash() function.

The signature is then derived by creating a hexadecimally encoded SHA256-HMAC of $encrypted and the message authentication key with the hash_hmac() function (denoted as $signature).

Store the private key

The private key is written to the $username.".privateKey" file with the derived $encrypted, $iv and $signature as documented in File type: private key file.

Encryption: generate the file key

Generate the file key

The file key is generated as a random string of 32 bytes with the random_bytes() function (denoted as $filekey).

Read the public key

The public keys of the recipients are read from the $username.".publicKey" files as documented in File type: public key file.

Encrypt/seal the file key

The file key is encrypted/sealed with the openssl_seal() function with the public keys. This returns the encrypted file key and the encrypted envelope keys for the recipients.

Store the file key

The encrypted file key is stored in the "fileKey" file as documented in File type: file key file.

Store the envelope keys

The encrypted envelope keys for the recipients are stored in the $username.".shareKey" files as documented in File type: share key file.

Encryption: encrypt the file

Split the file

The file is split into 6072 bytes sized blocks. Only the last encrypted block may be shorter. Each block is referenced by its zero-based index within the file (denoted as $position).

Encrypt the blocks

For each block the initialization vector is generated as a random string of 16 bytes with the random_bytes() function (denoted as $iv[$position]). The block is (by default) AES-256-CTR encrypted with the $iv[$position] and the $filekey with the openssl_encrypt() function and returned as Base64 encoded without zero-padding (denoted as $encrypted[$position]).

Sign the blocks

The message authentication key is derived by creating a raw SHA512 hash of $filekey.$version.$position."a" with the hash() function.

The signature is then derived by creating a hexadecimally encoded SHA256-HMAC of $encrypted[$position] and the message authentication key with the hash_hmac() function (denoted as $signature[$position]).

Store the file

The encrypted file is written to the file with the derived $encrypted[0..$n], $iv[0..$n] and $signature[0..$n] as documented in File type: file.

Decryption: read the private key

Read the private key file

The private key is read from the $username.".privateKey" file and the values $encrypted, $iv and $signature are parsed as documented in File type: private key file.

Derive the decryption key

The salt for the decryption key is derived by creating a raw SHA256 hash of $uid.$instanceId.$instanceSecret with the hash() function. $instanceId can be retrieved as instanceid from the config.php. $instanceSecret can be retrieved as secret from the config.php.

The decryption key is then derived by creating a raw SHA256-PBKDF2 hash of the password with the salt, 100.000 rounds and (by default) with a target size of 32 bytes (as required for AES-256-CTR) with the hash_hmac() function (denoted as $passphrase).

The used password depends on the key type:

Check the signature

The message authentication key is derived by creating a raw SHA512 hash of $passphrase.$version.$position."a" with the hash() function.

The signature is then derived by creating a hexadecimally encoded SHA256-HMAC of $encrypted and the message authentication key with the hash_hmac() function. Only proceed when the derived signature is equal to $signature which is checked with the hash_equals() function.

Decrypt the private key

The private key is (by default) AES-256-CTR decrypted with the $iv and the $passphrase with the openssl_decrypt() function.

Decryption: read the file key

Read the file key

The encrypted file key is read from the "fileKey" file as documented in File type: file key file.

Read the envelope key

The encrypted envelope key for the recipient is read from the $username.".shareKey" file as documented in File type: share key file.

Decrypt/unseal the file key

The encrypted file key is decrypted/unsealed with the openssl_open() function with the private key and encrypted envelope key for the recipient (denoted as $filekey).

Decryption: decrypt the file

Split the file

The encrypted file is split into a 8192 bytes sized header and one or more 8192 bytes sized blocks. Only the last encrypted block may be shorter. Each block is referenced by its zero-based index within the file (denoted as $position). The values $encrypted[0..$n], $iv[0..$n] and $signature[0..$n] are parsed as documented in File type: file.

Check the block signatures

The message authentication key is derived by creating a raw SHA512 hash of $filekey.$version.$position."a" with the hash() function.

The signature is then derived by creating a hexadecimally encoded SHA256-HMAC of $encrypted[$position] and the message authentication key with the hash_hmac() function. Only proceed when the derived signature is equal to $signature[$position] which is checked with the hash_equals() function.

Decrypt the blocks

Each block is (by default) AES-256-CTR decrypted with the $iv[$position] and the $filekey with the openssl_decrypt() function.

Sources

Server-side encryption migration

Encryption format

Nextcloud still supports the legacy encryption scheme used for server side encryption where the encrypted files did not contain header information. This may still be used for installations that still have encrypted files from <= ownCloud 6. Files will be updated to the new encryption format once they are written again. However it is recommended to check if you have to still support this scheme.

Starting with version 20 for new installations the legacy encryption will be off by default. However if you are upgrading there is a migration path to check if you can disable legacy encryption.

Checking for old files

On the command line run:

occ encryption:scan:legacy-format

The command will tell you if you can remove the legacy encryption mode. If so set the encryption.legacy_format_support in your config.php to 'false'.

Transactional file locking

Nextcloud's Transactional File Locking mechanism locks files to avoid file corruption during normal operation. It performs these functions:

What Transactional File locking is not for: it will not prevent multiple users from editing the same document, or give notice that other users are working on the same document. Multiple users can open and edit a file at the same time and Transactional File locking does not prevent this. Rather, it prevents simultaneous file saving.

Transactional File locking will use the database locking backend by default. This places a significant load on your database. Setting memcache.locking relieves the database load and improves performance. Admins of Nextcloud servers with heavy workloads should install a memcache. (See Memory caching.)

To use a memcache with Transactional File Locking, you must install a key-value store server like Valkey or Redis. Two cache backends are available for it:

Using the Nextcloud KeyValueCache cache

The KeyValueCache cache is built on a library bundled with Nextcloud, so no PHP module needs to be installed — you only need a running Valkey or Redis compatible server. Enter a configuration in your config.php file like this example:

'memcache.locking' => '\OC\Memcache\KeyValueCache',
'memcache.kvstore' => [
     'server' => [
          'host' => 'localhost',
          'port' => 6379,
     ],
     'password' => '', // Optional, if not defined no password will be used.
],

See Redis / Valkey using the Nextcloud KeyValueCache for all available options, including Unix sockets, TLS, Sentinel and cluster setups.

Using the Redis cache with the phpredis PHP module

To use the Redis cache instead, you must install the Redis server and corresponding PHP module. After installing Redis you must enter a configuration in your config.php file like this example:

'memcache.locking' => '\OC\Memcache\Redis',
'redis' => array(
     'host' => 'localhost',
     'port' => 6379,
     'timeout' => 0.0,
     'password' => '', // Optional, if not defined no password will be used.
      ),

提示

For enhanced security it is recommended to configure your key-value store server to require a password. See http://redis.io/topics/security or https://valkey.io/topics/security/ for more information.

If you want to configure Redis to listen on an Unix socket (which is recommended if Redis is running on the same system as Nextcloud) use this example config.php configuration:

'memcache.locking' => '\OC\Memcache\Redis',
'redis' => array(
     'host' => '/run/redis/redis-server.sock',
     'port' => 0,
     'timeout' => 0.0,
      ),

See config.sample.php to see configuration examples for Redis, and for all supported memcaches.

Learn more about Redis at Redis. Memcached, the popular distributed memory caching system, is not suitable for the new file locking because it is not designed to store locks, and data can disappear from the cache at any time. Redis is a key-value store, and it guarantees that cached objects are available for as long as they are needed.

Previews configuration

The Nextcloud thumbnail system generates previews of files for all Nextcloud apps that display files, such as Files and Gallery.

The following image shows some examples of previews of various file types.

Thumbnails of various image and audio/video files.

By default, Nextcloud can generate previews for the following filetypes:

提示

Nextcloud can also generate previews of other file types (such as PDF, SVG, various Office document formats, and various video formats). Due to security and performance concerns those providers are disabled by default. While those providers are still available, we discourage enabling them and they are considered unsupported. The full list of the preview providers that are enabled by default (as well as those disabled by default) can be found under the enabledPreviewProviders configuration parameter.

Some preview providers depend on external binaries on the server. Video previews such as OC\Preview\Movie and OC\Preview\MKV require ffmpeg. Office document previews such as OC\Preview\OpenDocument and OC\Preview\MSOfficeDoc require LibreOffice. Image formats handled through ImageMagick, such as OC\Preview\Illustrator, OC\Preview\SVG and OC\Preview\TIFF, require the corresponding ImageMagick support.

Parameters

Please notice that the Nextcloud preview system comes already with sensible defaults, and therefore it is usually unnecessary to adjust those configuration values.

But deemed necessary, following changes have to be made in config/config.php file. As a best practice, take a backup of this config file before making a lot of changes.

After changing one or more of the following parameters, you might want to run the preview:cleanup occ command to get rid of the previews with obsolete settings. See Preview to learn more.

Disabling previews:

Under certain circumstances, for example if the server has limited resources, you might want to consider disabling the generation of previews. Note that if you do this all previews in all apps are disabled, including the Gallery app, and will display generic icons instead of thumbnails.

Set the configuration option enable_previews to false:

<?php
  'enable_previews' => false,

Maximum preview size:

There are two configuration options to set the maximum size of a preview.

<?php
  'preview_max_x' => null,
  'preview_max_y' => null,

By default, both options are set to null. 'Null' is equal to no limit. Numeric values represent the size in pixels. The following code limits previews to a maximum size of 100×100px:

<?php
  'preview_max_x' => 100,
  'preview_max_y' => 100,

'preview_max_x' represents the x-axis and 'preview_max_y' represents the y-axis.

Maximum scale factor:

If a lot of small pictures are stored on the Nextcloud instance and the preview system generates blurry previews, you might want to consider setting a maximum scale factor. By default, pictures are upscaled to 10 times the original size:

<?php
  'preview_max_scale_factor' => 10,

If you want to disable scaling at all, you can set the config value to '1':

<?php
  'preview_max_scale_factor' => 1,

If you want to disable the maximum scaling factor, you can set the config value to 'null':

<?php
  'preview_max_scale_factor' => null,

JPEG quality setting:

Default JPEG quality setting for preview images is '80'. Change this with:

occ config:app:set preview jpeg_quality --value="60"

Maximum memory for image generation:

By default, Nextcloud generates image previews using the GD Graphics Library. This configuration option limits the amount of memory that is allowed for preview generation. If creating the preview image would allocate more memory than the limit, preview generation will be disabled and the default mimetype icon is shown.

Default limit is 256 MB. Set to -1 for no limit.

<?php
  'preview_max_memory' => 256,

Controlling file versions and aging

The Versions app (files_versions) expires old file versions automatically to ensure that users don't exceed their storage quotas. This is the default pattern used to delete old versions:

The versions are adjusted along this pattern every time a new version is created. Nextcloud will always keep the latest version in each of the time windows.

The Versions app never uses more than 50% of the user's currently available free space. If the stored versions exceed this limit, Nextcloud deletes the oldest file versions until it meets the disk space limit again.

Nextcloud manages file versions using a combination of on-save pruning and scheduled cleanup. This ensures that versions are retained while respecting storage quotas.

During Version Creation

Nextcloud automatically creates new file versions whenever a file is modified, allowing users to restore previous states when needed. After each new version is stored, the system automatically checks storage limits and retention rules. Versions are filtered according to the above pattern to keep representative versions and remove redundant ones. If the user’s quota is exceeded, auto-expiry is triggered. When storage space runs low, Nextcloud sorts all versions from oldest to newest and removes the oldest ones first, while always preserving at least the two most recent versions to free up space.

During the Regular Background Job

Nextcloud runs a background cleanup task that automatically removes old file versions for each user. During this process, the system checks the user's version storage folder and identifies versions that are older than the configured maximum retention period or whose original files no longer exist. When an outdated or orphaned version is found, it is safely deleted from both the filesystem and the version database to reclaim storage space and maintain consistency.

提示

Versions named by a user will never be deleted.

You may alter the default pattern in config.php. The default setting is auto, which sets the default pattern:

'versions_retention_obligation' => 'auto',

Additional options are:

Background job

To delete expired versions a background jobs runs every 30 minutes. It's possible to deactivate the background job and setup a (system) cron to expire the versions via occ.

Deactivate background job: occ config:app:set --value=no files_versions background_job_expire_versions

Activate background job: occ config:app:delete files_versions background_job_expire_versions

Expire versions: occ versions:expire or occ versions:expire --quiet (without the progress bar)

Deleted Items (trash bin)

If the trash bin app is enabled (default), this setting defines the policy for when files and folders in the trash bin will be permanently deleted.

提示

If the user quota limit is exceeded due to deleted files in the trash bin, retention settings will be ignored and files will be cleaned up until the quota requirements are met.

The app allows for two settings, a minimum time for trash bin retention, and a maximum time for trash bin retention. Minimum time is the number of days a file will be kept, after which it may be deleted. Maximum time is the number of days at which it is guaranteed to be deleted. Both minimum and maximum times can be set together to explicitly define file and folder deletion. For migration purposes, this setting is installed initially set to "auto", which is equivalent to the default setting in Nextcloud.

You may alter the default pattern in config.php. The default setting is auto, which sets the default pattern:

'trashbin_retention_obligation' => 'auto',

Available values:

Background job

To permanently delete files a background jobs runs every 30 minutes. It's possible to deactivate the background job and setup a (system) cron to expire the versions via occ.

Deactivate background job: occ config:app:set --value=no files_trashbin background_job_expire_trash

Activate background job: occ config:app:delete files_trashbin background_job_expire_trash

Expire versions: occ trashbin:expire or occ trashbin:expire --quiet (without the progress bar)

File conversion

In the majority of cases, it is recommended that either the Pandoc or Nextcloud Office apps are enabled, as they provide the majority of file conversions available. Other apps may also support their own file conversions for other file types if more specific conversions are required.

Windows compatible filenames

提示

This feature was introduced in Nextcloud 31.

By default Nextcloud supports all filenames which are valid on the underlying server. As Nextcloud runs only on POSIX compatible operating systems (Linux), this means that Nextcloud supports also filenames not valid on Microsoft Windows systems.

If your users use Windows and use the Nextcloud Desktop clients to synchronize their work to their computer they might encounter files created in the web interface, or on a Linux machine, which cannot be synchronized as the filename is not valid.

To solve this issue it is possible to enforce filenames only valid on Windows, this for example forbids characters like * from filenames or filenames like AUX.txt (on Windows AUX is a reserved name and cannot be used).

提示

Enabling this setting will not enforce case-insensitivity as modern Windows systems support case-sensitive filenames.

Enabling Windows compatible filenames

This feature can be enabled either by using the web interface or by using an occ command.

提示

This feature works by setting a predefined set of system configuration settings. So after enabling this the config.php will be adjusted, which also means enabling this feature requires a writable configuration.

Using the web interface

The setting is provided in the Administration settings under Basic settings. Within the Files compatibility section the Windows compatibility can be enabled.

Enforce windows compatibility checkbox on the Administration - Basic settings - Files compatibility page.

Using the occ command

提示

This command was introduced in Nextcloud 32.

To quickly enable or disable the feature an occ command is provided.

Consequences

After enabling Windows compatible filenames users cannot create or modify files with invalid filenames. But they can still delete or rename those files (to valid names).

This works by setting a pre-defined set of configuration settings:

Sanitizing invalid filenames

After enabling the feature the users have to manually adjust all invalid filenames to be able to keep working with them. As an alternative Nextcloud provides the occ files:sanitize-filenames command to automatically rename all invalid files.

Flow

Flow configuration

Administrators can disable user flows since they can have an impact on the performance of a system and you might not want to give users the ability to define their own flows rules. They can be disabled through the following command:

occ config:app:set workflowengine user_scope_disabled --value yes

Files access control

Nextcloud's File Access Control app enables administrators to create and manage a set of rule groups. Each of the rule groups consists of one or more rules. If all rules of a group hold true, the group matches the request and access is being denied. The rules criteria range from IP address, to user groups, collaborative tags and some more.

提示

In case you are using the Context Chat App, please keep in mind, that it is not affected by the File Access Control rules and will respond with indexed information, even when the file is not accessible by the user due to access control rules.

Denied access

If access to a file has been denied for a user, the user can not:

Examples

After installing the File Access Control app as described in Apps management navigate to the configuration and locate the settings for the Flow application.

Sample rules to block on user group, time and IP base.

The first rule group Support only 9-5 denies any access to files for users of the Support user group, between 5pm and 9am.

The second rule group Internal testing prevents users of the Internal testers group to access files from outside of the local network.

Denying access to folders

The easiest way to block access to a folder, is to use a collaborative tag. As mentioned in the Available rules section below, either the file itself or one of the parents needs to have the given tag assigned.

So you just need to assign the tag to the folder or file, and then block the tag with a rule group. The check is independent of the user's permissions for the tag. Therefore restricted and invisible tags are recommended, otherwise a user could remove and reassign the tag.

This example blocks access to any folder with the tag Confidential.

Deny access based on collaborative tag

Prevent uploading of specific files

It's possible to prevent specific files from being uploaded to Nextcloud. You simply need to define a rule based on the mimetype and our powerful access control engine will block any attempt to upload the file. The safest way to define the rule is to use a regular expression, as it will help you cover all the known media types used for the type of file you're trying to block.

The following example prevents zip files from being uploaded by using the regular expression: /^application\/(zip|x-zip-compressed)$/i

Prevent upload based on mimetype

Common misconfigurations

Blocking user groups

When trying to deny access to a group of users, make sure that sharing does not allow them to create a way back in. When users are able to create a public link, the users can log themselves out and visit their own public link to access the files. Since at this point they are no user and therefore no member of the blocked group, they will be able to read and change the file.

External storage

While access to files in external storages is not possible via Nextcloud, users that have direct access to the external storage, can of course change files there directly. Therefore it is recommended to disable the Allow users to mount external storage option, when trying to to completely lock out users.

Available rules

All rules can also be inverted (from is to is not) using the operator option.

Automated tagging of files

Nextcloud's Files Automated Tagging app allows to assign collaborative tags to files and folders based on rules, similar to Files access control.

Assigning restricted and invisible tags

The main functionality of this app is to allow users to indirectly assign restricted and invisible tags to files they upload.

This is especially useful for retention and Files access control, so people that got the files shared can not remove the tag to stop the retention or allow access against the owner's will.

Example

After installing the Files automated tagging app as described in Apps management navigate to the configuration and locate the Workflow settings.

Example rule to assign a restricted tag.

In the example you can see a simple rule with only one condition. It will tag all files with the restricted tag Protected file that are uploaded into a folder that is tagged with Protect content. No user can remove the tag Protected file and therefore access control and retention both work fine without users being able to work around them.

In this case the folder will also be tagged with tag Protected file, to avoid this, simply modify the rule to exclude Directory httpd/unix-directory from it.

Example rule to assign a restricted tag except to Directory.

Available rules

The available rules can be seen in the access control section: Available rules.

提示

Please note that the rules do not apply when creating external storages and groupfolders. The root folders of those need to be tagged manually with the desired initial tags. Items created inside later on apply the rules as defined.

Executing actions

It is possible to execute actions like `convert to PDF based on assigned tags. Nextcloud GmbH assists customers in this with hands-on help and documentation on our `customer portal <https://portal.nextcloud.com>_.

Retention of files

Nextcloud's Files Retention app allows to automatically delete files that are tagged with a collaborative tag and have a certain age.

Example

After installing the Retention app as described in Apps management navigate to Administration settings and then to Flow.

Sample rule to delete files after 14 days after creation.

The rule from the example will delete all files tagged with Temporary file 14 days after the creation.

You can also use the "Notify owner a day before a file is automatically deleted" option to make sure the file owner will get a notification before a file will be deleted.

File age

There are 2 options available that can be used to decide when to delete a file:

Common misconfigurations

Public collaborative tag

Similar to Files access control retention should use restricted or invisible tags. Otherwise any user can remove the tag and the file is not removed after the given period. Use Automated tagging of files to assign such tags to newly uploaded files.

Mimetypes management

Mimetype aliases

Nextcloud allows you to create aliases for mimetypes, so that you can display custom icons for files. For example, you might want a nice audio icon for audio files instead of the default file icon.

By default Nextcloud is distributed with nextcloud/resources/config/mimetypealiases.dist.json. Do not modify this file, as it will be replaced when Nextcloud is updated. Instead, create your own nextcloud/config/mimetypealiases.json file with your custom aliases. Use the same syntax as in nextcloud/resources/config/mimetypealiases.dist.json.

Once you have made changes to your mimetypealiases.json, use the occ command to propagate the changes through the system. This example is for Ubuntu Linux:

$ sudo -E -u www-data php occ maintenance:mimetype:update-js

# you may also need to update the mimetype for existing files, see nextcloud/server#30566
$ sudo -E -u www-data php occ maintenance:mimetype:update-db --repair-filecache

See Using the occ command to learn more about occ.

Some common mimetypes that may be useful in creating aliases are:

image
Generic image

image/vector
Vector image

audio
Generic audio file

x-office/document
Word processed document

x-office/spreadsheet
Spreadsheet

x-office/presentation
Presentation

text
Generic text document

text/code
Source code

Mimetype mapping

Nextcloud allows administrators to specify the mapping of a file extension to a mimetype. For example files ending in mp3 map to audio/mpeg. Which then in turn allows Nextcloud to show the audio icon.

By default Nextcloud comes with mimetypemapping.dist.json. This is a simple json array. Administrators should not update this file as it will get replaced on upgrades of Nextcloud. Instead the file mimetypemapping.json should be created and modified, this file has precedence over the shipped file.

Icon retrieval

When an icon is retrieved for a mimetype, if the full mimetype cannot be found, the search will fallback to looking for the part before the slash. Given a file with the mimetype 'image/my-custom-image', if no icon exists for the full mimetype, the icon for 'image' will be used instead. This allows specialised mimetypes to fallback to generic icons when the relevant icons are unavailable.