# Configuration

# Nextcloud configuration

- [Warnings on admin page](/link/918)
- [Configuration Parameters](/link/919)
- [Activity app](/link/920)
- [Administration privileges (Delegation)](/link/921)
- [Android Deep Link Handling](/link/922)
- [Antivirus scanner](/link/923)
- [Background jobs](/link/924)
- [Brute force protection](/link/925)
- [Memory caching](/link/926)
- [Configuration Parameters](/link/919)
- [Dashboard app](/link/927)
- [Domain Change](/link/928)
- [Email](/link/929)
- [Linking external sites](/link/930)
- [Nextcloud configuration](/link/917)
- [Language & Locale](/link/931)
- [Logging](/link/932)
- [OAuth2](/link/933)
- [Reverse proxy](/link/934)
- [Warnings on admin page](/link/918)
- [Text app](/link/935)
- [Theming](/link/936)


# Warnings on admin page

Your Nextcloud server has a built-in configuration checker, and it reports its findings at the top of your Admin page. These are some of the warnings you might see, and what to do about them.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/security-setup-warning-1.png)

You can use the [Nextcloud Security Scan](https://scan.nextcloud.com) to see if your system is up to date and well secured. We have ran this scan over public IP addresses in the past to try and reach out to [extremely outdated systems](https://nextcloud.com/blog/nextcloud-releases-security-scanner-to-help-protect-private-clouds/) and might again in the future. Please, protect your privacy and keep your server up to date! Privacy means little without security.

## Cache warnings

"No memory cache has been configured. To enhance your performance please configure a memcache if available." Nextcloud supports multiple php caching extensions:

- APCu (minimum required PHP extension version 4.0.6)
- Memcached
- Redis (minimum required PHP extension version: 2.2.6)

You will see this warning if you have no caches installed and enabled, or if your cache does not have the required minimum version installed; older versions are disabled because of performance problems.

If you see "*{Cache}* below version *{Version}* is installed. for stability and performance reasons we recommend to update to a newer *{Cache}* version" then you need to upgrade, or, if you're not using it, remove it.

You are not required to use any caches, but caches improve server performance. See [Memory caching](/link/926).

## Transactional file locking is disabled

"Transactional file locking is disabled, this might lead to issues with race conditions."

Please see [Transactional file locking](/link/969) on how to correctly configure your environment for transactional file locking.

## You are accessing this site via HTTP

"You are accessing this site via HTTP. We strongly suggest you configure your server to require using HTTPS instead." Please take this warning seriously; using HTTPS is a fundamental security measure. You must configure your Web server to support it, and then there are some settings in the **Security** section of your Nextcloud Admin page to enable. The following pages describe how to enable HTTPS on the Apache and Nginx Web servers.

[Enabling SSL](/link/897) (on Apache)

[Use HTTPS](/link/903)

[NGINX configuration](/link/902)

## The test with getenv("PATH") only returns an empty response

Some environments are not passing a valid PATH variable to Nextcloud. The [PHP-FPM configuration](/link/897) provides the information about how to configure your environment.

## The "Strict-Transport-Security" HTTP header is not configured

"The "Strict-Transport-Security" HTTP header is not configured to least "15552000" seconds. For enhanced security we recommend enabling HSTS as described in our security tips."

The HSTS header needs to be configured within your Web server by following the [Enable HTTP Strict Transport Security](/link/903) documentation

You can see if the header is appearing in requests by using your browser inspector or using a tool such as cURL: `curl --head https://cloud.domain.tld`.

## /dev/urandom is not readable by PHP

"/dev/urandom is not readable by PHP which is highly discouraged for security reasons. Further information can be found in our documentation."

This message is another one which needs to be taken seriously. Please have a look at the [Give PHP read access to /dev/urandom](/link/903) documentation.

## Your Web server is not yet set up properly to allow file synchronization

"Your web server is not yet set up properly to allow file synchronization because the WebDAV interface seems to be broken."

At the ownCloud community forums a larger [FAQ](https://forum.owncloud.org/viewtopic.php?f=17&t=7536) is maintained containing various information and debugging hints.

## Outdated NSS / OpenSSL version

"cURL is using an outdated OpenSSL version (OpenSSL/\$version). Please update your operating system or features such as installing and updating apps via the app store or Federated Cloud Sharing will not work reliably."

"cURL is using an outdated NSS version (NSS/\$version). Please update your operating system or features such as installing and updating apps via the app store or Federated Cloud Sharing will not work reliably."

There are known bugs in older OpenSSL and NSS versions leading to misbehavior in combination with remote hosts using SNI. A technology used by most of the HTTPS websites. To ensure that Nextcloud will work properly you need to update OpenSSL to at least 1.0.2b or 1.0.1d. For NSS the patch version depends on your distribution and an heuristic is running the test which actually reproduces the bug.

## Your Web server is not set up properly to resolve /.well-known/caldav/ or /.well-known/carddav/

Both URLs need to be correctly redirected to the DAV endpoint of Nextcloud. Please refer to [Service discovery](/link/1071) for more info.

## Some files have not passed the integrity check

Please refer to the [Fixing invalid code integrity messages](/link/1073) documentation how to debug this issue.

## Your database does not run with "READ COMMITTED" transaction isolation level

"Your database does not run with "READ COMMITTED" transaction isolation level. This can cause problems when multiple actions are executed in parallel."

Please refer to [Database "READ COMMITTED" transaction isolation level](/link/911) how to configure your database for this requirement.

## The "\_\_Host-" prefix is not used for the cookie name

"The `__Host-` prefix is not used for the cookie name. It is recommended to enable this in your configuration."

Nextcloud applies the `__Host-` prefix to its same-site CSRF cookies (`__Host-nc_sameSiteCookiestrict` and `__Host-nc_sameSiteCookielax`) when it detects that the connection is served over HTTPS. The prefix instructs browsers to only accept those cookies over a secure connection and from the exact host that set them, which strengthens CSRF protection.

This warning appears when Nextcloud cannot confirm it is running over HTTPS. The most common cause is a **reverse proxy** that terminates TLS and forwards requests to Nextcloud over plain HTTP. In that case Nextcloud sees HTTP internally and omits the prefix.

To fix this, tell Nextcloud to treat the connection as HTTPS by adding `overwriteprotocol` to `config/config.php`:

    'overwriteprotocol' => 'https',

If you are not behind a reverse proxy, ensure your web server is configured to serve Nextcloud exclusively over HTTPS. See the [Use HTTPS](/link/903) documentation.

For background on the cookies themselves, see [Cookies](/link/889).


# Configuration Parameters

## Introduction

Nextcloud uses `config/config.php` as its main configuration file. This file controls various fundamental aspects of server operations. It is typically modified as part of initial deployment, when troubleshooting, and when making adjustments to surrounding infrastructure.

This is a required file for all Nextcloud deployments and thus it is critical for Nextcloud administrators to be familiar with managing it.

This section of the *Administration Manual* documents how to adjust this essential file, certain special characteristics of the `config/` directory, and all of the supported parameters that can be specified in a `config/config.php` file.

> **提示**
>
> While `config/config.php` is a required file, many Nextcloud or Nextcloud app settings are managed elsewhere and thus not included in it. These settings are typically managed via individual apps.

## Loading

Configuration files located in `config/` are parsed automatically when Nextcloud starts up. They are also checked for changes periodically (approximately every two seconds in a standard PHP environment running with default *OPcache* settings; approximately every sixty seconds in many pre-packaged Nextcloud installation methods).

The `config/config.php` file may be supplemented by additional `*.config.php` files placed in the `config/` directory (if appropriately named and formatted).

> **警告**
>
> Be cautious when naming or creating backup copies of your active `config/config.php`. If a backup is located within `config/` and is named `(ANYTHING).config.php`, it will be loaded as part of your live configuration and override your `config/config.php` values!

> **提示**
>
> If your configuration changes don't seem to be taking effect, check: (a) your PHP opcache configuration; (b) for additional `*.config.php` files located in `config/`; (c) the documentation for your Nextcloud installation method/package; (d) the output of `occ config:list system`.

## Format

The short answer is that `config/` files are plain text files with some special formatting requirements for different types of parameters and values. This makes it extensible and easy for Nextcloud to interact with. It also makes it easy for administrators to view with any text viewer and from the command-line.

Technically these configuration files are PHP files containing a special (to Nextcloud) PHP array called `$CONFIG`. This array consists of various Nextcloud specific "key-value" pairs (in some cases arrays themselves). Each pair has the form `key => value` and is comma-separated.

### Types of Values

Strings:

- `"thisIsAnImportantValue"`

- Note: These must be either single or double quoted - i.e. `"string"` or `'string'`.

- Note: IP addresses are considered strings.

- Examples:  
  - `'logo_url' => 'https://example.org',`
  - `'versions_retention_obligation' => 'auto, D',`
  - `'logtimezone' => 'Europe/Berlin',`

Boolean:

- `true` or `false`

- Note: These should **not** be surrounded by quote marks within the configuration file itself.

- Examples:  
  - `'session_keepalive' => true,`
  - `'hide_login_form' => false,`

Numerical:

- `12`

- This includes both integers and floating point numbers.

- Note: These should **not** be surrounded by quote marks within the configuration file itself.

- Examples:  
  - `'loglevel' => 2,`
  - `'session_lifetime' => 60 * 60 * 24,`

Arrays of any of the above types:

- `[ 'value1', 'value2' ]`

- All value types (including other arrays) can be included in arrays.

- Note: Only some parameters support array style values.

- Examples:  
  - `'connectivity_check_domains' => [ 'www.nextcloud.com', 'www.eff.org', ],`
  - `'enabledPreviewProviders' => [ 'OC\Preview\BMP', 'OC\Preview\GIF', 'OC\Preview\JPEG', ],`

> **提示**
>
> Nextcloud attempts to remedy some value type/formatting mistakes, but this is not foolproof. Use the correct formatting (for the type of value in question) to avoid unexpected results arising from values being cast in unexpected ways.

## Modifying

Parameters may be modified in a standard text editor (i.e. via the command-line or externally then re-uploaded). They may also, in most cases, be modified using the commands in the `occ config:system:*` namespace.

> **提示**
>
> Incorrectly formatted `key => value` entries (or incorrectly specified values) may not generate immediate errors or problems (such as parsing / syntax errors), but may still lead to unexpected and undesirable results. Review your fully parsed (by PHP) configuration by using the command `occ config:list system` and/or `occ config:list system --private` to identify anything unexpected.

## Defaults

Nextcloud creates a base `config/config.php` file at installation time containing the most essential parameters for operations. These values are a mixture of auto-generated and drawn from information provided by the administrator at installation time.

The file `config/config.sample.php` lists all the parameters within Nextcloud that can be specified in `config/` files, along with example and default values for each. The content of that sample configuration file is included [below](/link/919) for ease of reference and alongside additional context.

> **提示**
>
> Only add parameters to `config/config.php` that you wish to modify.

> **警告**
>
> Do not copy everything from `config/config.sample.php` into your own `config/config.php`! Besides being unnecessary, it will break things and possibly even require re-installation.

## Multiple/Merged Configuration Files

Nextcloud supports loading configuration parameters from multiple files. You can add arbitrary files ending with `.config.php*` (i.e. `*.config.php`) in the `config/` directory. The values in these files take precedence over `config/config.php`. This allows you to easily create and manage custom configurations, or to divide a large complex configuration file into a set of smaller files. These custom files are not overwritten by Nextcloud.

For example, you could place your email server configuration in `config/email.config.php` and whatever parameters you specify in it will be merged with your `config/config.php`.

> **提示**
>
> The values in these additional configuration files **always** take precedence over `config/config.php`.

> **提示**
>
> To view your fully merged configuration (i.e. incorporating all config files), use `occ config:list system` and/or `occ config:list system --private`.

> **警告**
>
> Be cautious when naming or creating backup copies of your active `config/config.php`. If a backup config file is located within `config/` and happens to be named `(ANYTHING).config.php`, it will be loaded as part of your live configuration and override your `config/config.php` values!

## Environment Variables

The `NEXTCLOUD_CONFIG_DIR` environment variable overrides the default config directory path. When set, Nextcloud loads `config.php` (and any `*.config.php` files) from that path instead of the `config/` directory inside the webroot.

``` bash
NEXTCLOUD_CONFIG_DIR=/etc/nextcloud php /var/www/nextcloud/cron.php
```

This is useful for:

- Moving `config.php` outside the webroot as a hardening measure — credentials are not accessible via HTTP even if directory listing is enabled or misconfigured.
- Running multiple Nextcloud instances that share a single codebase but require separate config directories.

> **提示**
>
> `NEXTCLOUD_CONFIG_DIR` must be set for **both** the web server process and any CLI invocations (`occ`, cron jobs). Set it in your web server virtual host configuration and in the shell environment used for CLI work.

> **另见**
>
> [Place config directory outside of the web root](/link/903) in the hardening guide for a deployment recommendation.

## Examples

These are some examples of the content of typical `config/config.php` files immediately after a basic installation of Nextcloud.

When you use SQLite as your Nextcloud database, your `config.php` looks like this after installation. The SQLite database is stored in your Nextcloud `data/` directory:

    <?php
    $CONFIG = array (
      'instanceid' => 'occ6f7365735',
      'passwordsalt' => '2c5778476346786306303',
      'trusted_domains' =>
      array (
        0 => 'localhost',
        1 => 'studio',
      ),
      'datadirectory' => '/var/www/nextcloud/data',
      'dbtype' => 'sqlite3',
      'version' => '7.0.2.1',
      'installed' => true,
    );

> **提示**
>
> SQLite is a simple, lightweight embedded database that is fine for testing and simple installations, but production environments you should use MySQL/MariaDB, Oracle, or PosgreSQL.

This example is from a new Nextcloud installation using MariaDB:

    <?php
    $CONFIG = array (
      'instanceid' => 'oc8c0fd71e03',
      'passwordsalt' => '515a13302a6b3950a9d0fdb970191a',
      'trusted_domains' =>
      array (
        0 => 'localhost',
        1 => 'studio',
        2 => '192.168.10.155'
      ),
      'datadirectory' => '/var/www/nextcloud/data',
      'dbtype' => 'mysql',
       'version' => '7.0.2.1',
      'dbname' => 'nextcloud',
      'dbhost' => 'localhost',
      'dbtableprefix' => 'oc_',
      'dbuser' => 'oc_carla',
      'dbpassword' => '67336bcdf7630dd80b2b81a413d07',
      'installed' => true,
    );

## Default Parameters

These parameters are configured by the Nextcloud installer, and are required for your Nextcloud server to operate.

### instanceid

    'instanceid' => '',

This is a unique identifier for your Nextcloud installation, created automatically by the installer. This example is for documentation only, and you should never use it because it will not work. A valid `instanceid` is created when you install Nextcloud.

### serverid

    'serverid' => -1,

This is a unique identifier for your server.

It is useful when your Nextcloud instance is using different PHP servers. Once it's set it shouldn't be changed.

Value must be an integer, comprised between 0 and 511.

When config.php is shared between different servers, this value should be overridden with "NC_serverid=\<int\>" on each server. Note that it must be overridden for CLI and for your webserver.

Example for CLI: NC_serverid=42 occ config:list system

### passwordsalt

    'passwordsalt' => '',

The salt used to hash all passwords, auto-generated by the Nextcloud installer. (There are also per-user salts.) If you lose this salt, you lose all your passwords. This example is for documentation only, and you should never use it.

> *Deprecated since version 9.0.0:* This salt is deprecated and only used for legacy-compatibility, developers should *NOT* use this value for anything nowadays.

### secret

    'secret' => '',

Secret used by Nextcloud for various purposes, e.g., to encrypt data. If you lose this string, there will be data corruption.

### trusted_domains

    'trusted_domains' => [
            'demo.example.org',
            'otherdomain.example.org',
            '10.111.112.113',
            '[2001:db8::1]'
        ],

Your list of trusted domains that users can log into. Specifying trusted domains prevents host header poisoning. Do not remove this, as it performs necessary security checks.

You can specify:

- The exact hostname of your host or virtual host, e.g. `demo.example.org`.
- The exact hostname with permitted port, e.g. `demo.example.org:443`. This disallows all other ports on this host
- Use `*` as a wildcard, e.g., `ubos-raspberry-pi*.local` will allow `ubos-raspberry-pi.local` and `ubos-raspberry-pi-2.local`
- The IP address with or without permitted port, e.g. `[2001:db8::1]:8080` Using TLS certificates where `commonName=<IP address>` is deprecated

### cookie_domain

    'cookie_domain' => '',

The validity domain for cookies, for example `''` (cookies will be sent only the domain that defined it, e.g. `'demo.example.org'`), `'demo.example.org'` (cookies will be valid for the domain and all subdomains), ...

Defaults to `''` (safe option)

### datadirectory

    'datadirectory' => '/var/www/nextcloud/data',

Where user files are stored. The SQLite database is also stored here, when you use SQLite.

Default to `data/` in the Nextcloud directory.

### version

    'version' => '',

The current version number of your Nextcloud installation. This is set up during installation and update, so you shouldn't need to change it.

### dbtype

    'dbtype' => 'sqlite3',

Identifies the database used with this installation. See also config option `supportedDatabases`

Available:  
- sqlite3 (SQLite3)
- mysql (MySQL/MariaDB)
- pgsql (PostgreSQL)

Defaults to `sqlite3`

### dbhost

    'dbhost' => '',

Your host server name, for example `localhost`, `hostname`, `hostname.example.com`, or the IP address.

To specify a port, use `hostname:####`; for IPv6 addresses, use the URI notation `[ip]:port`. To specify a Unix socket, use `localhost:/path/to/directory/containing/socket` or `:/path/to/directory/containing/socket`, e.g., `localhost:/run/postgresql/`.

### dbname

    'dbname' => 'nextcloud',

The name of the Nextcloud database, which is set during installation. You should not need to change this.

### dbuser

    'dbuser' => '',

The user that Nextcloud uses to write to the database. This must be unique across Nextcloud instances using the same SQL database. This is set up during installation, so you shouldn't need to change it.

### dbpassword

    'dbpassword' => '',

The password for the database user. This is set up during installation, so you shouldn't need to change it.

### dbtableprefix

    'dbtableprefix' => 'oc_',

Prefix for the Nextcloud tables in the database.

Default to `oc_`

### dbpersistent

    'dbpersistent' => '',

Enable persistent connections to the database.

This setting uses the `persistent` option from Doctrine DBAL, which in turn uses the PDO::ATTR_PERSISTENT option from the PDO driver.

### dbreplica

    'dbreplica' => [
            ['user' => 'nextcloud', 'password' => 'password1', 'host' => 'replica1', 'dbname' => ''],
            ['user' => 'nextcloud', 'password' => 'password2', 'host' => 'replica2', 'dbname' => ''],
        ],

Specify read-only replicas to be used by Nextcloud when querying the database

### db.log_request_id

    'db.log_request_id' => false,

Add request ID to the database query in a comment.

This can be enabled to assist in mapping database logs to Nextcloud logs.

### installed

    'installed' => false,

Indicates whether the Nextcloud instance was installed successfully; `true` indicates a successful installation, and `false` indicates an unsuccessful installation.

Defaults to `false`

## User Experience

These optional parameters control some aspects of the user interface. Default values, where present, are shown.

### default_language

    'default_language' => 'en',

This sets the default language on your Nextcloud server, using ISO_639-1 language codes such as `en` for English, `de` for German, and `fr` for French. The default_language parameter is only used when the browser does not send any language, and the user hasn’t configured their own language preferences.

Nextcloud has two distinguished language codes for German, `de` and `de_DE`. `de` is used for informal German and `de_DE` for formal German. By setting this value to `de_DE`, you can enforce the formal version of German unless the user has chosen something different explicitly.

Defaults to `en`

### force_language

    'force_language' => 'en',

With this setting, a language can be forced for all users. If a language is forced, the users are also unable to change their language in the personal settings. If users shall be unable to change their language, but users have different languages, this value can be set to `true` instead of a language code.

Defaults to `false`

### default_locale

    'default_locale' => 'en_US',

This sets the default locale on your Nextcloud server, using ISO_639 language codes such as `en` for English, `de` for German, and `fr` for French, and ISO-3166 country codes such as `GB`, `US`, `CA`, as defined in RFC 5646. It overrides automatic locale detection on public pages like login or shared items. User's locale preferences configured under "personal -\> locale" override this setting after they have logged in.

Defaults to `en`

### reduce_to_languages

    'reduce_to_languages' => [],

With this setting, it is possible to reduce the languages available in the language chooser. The languages have to be set as array values using ISO_639-1 language codes such as `en` for English, `de` for German, etc.

For example: Set to `['de', 'fr']` to only allow German and French languages.

### default_phone_region

    'default_phone_region' => 'GB',

This sets the default region for phone numbers on your Nextcloud server, using ISO 3166-1 country codes such as `DE` for Germany, `FR` for France, … It is required to allow inserting phone numbers in the user profiles starting without the country code (e.g., +49 for Germany).

No default value!

### force_locale

    'force_locale' => 'en_US',

With this setting, a locale can be forced for all users. If a locale is forced, the users are also unable to change their locale in the personal settings. If users shall be unable to change their locale, but users have different languages, this value can be set to `true` instead of a locale code.

Defaults to `false`

### default_timezone

    'default_timezone' => 'Europe/Berlin',

This sets the default timezone on your Nextcloud server, using IANA identifiers like `Europe/Berlin` or `Pacific/Auckland`. The default timezone parameter is only used when the timezone of the user cannot be determined.

Defaults to `UTC`

### knowledgebaseenabled

    'knowledgebaseenabled' => true,

`true` enables the Help menu item in the user menu (top right of the Nextcloud Web interface).

`false` removes the Help item.

### knowledgebase.embedded

    'knowledgebase.embedded' => false,

`true` embeds the documentation in an iframe inside Nextcloud.

`false` only shows buttons to the online documentation.

### allow_user_to_change_display_name

    'allow_user_to_change_display_name' => true,

`true` allows users to change their display names (on their Personal pages), and `false` prevents them from changing their display names.

### skeletondirectory

    'skeletondirectory' => '/path/to/nextcloud/core/skeleton',

The directory where the skeleton files are located. These files will be copied to the data directory of new users. Set empty string to not copy any skeleton files. If unset and templatedirectory is an empty string, shipped templates will be used to create a template directory for the user.

`{lang}` can be used as a placeholder for the language of the user. If the directory does not exist, it falls back to non-dialect (from `de_DE` to `de`). If that does not exist either, it falls back to `default`

Defaults to `core/skeleton` in the Nextcloud directory.

### templatedirectory

    'templatedirectory' => '/path/to/nextcloud/templates',

The directory where the template files are located. These files will be copied to the template directory of new users. Set empty string to not copy any template files.

`{lang}` can be used as a placeholder for the language of the user. If the directory does not exist, it falls back to non-dialect (from `de_DE` to `de`). If that does not exist either, it falls back to `default`

To disable creating a template directory, set both skeletondirectory and templatedirectory to empty strings.

## User session

### remember_login_cookie_lifetime

    'remember_login_cookie_lifetime' => 60 * 60 * 24 * 15,

Lifetime of logins where the user selected "Remember me", in seconds.

A value \> `0` means "Remember me" is available. To make "Remember me" unavailable to users, set to `0`.

To avoid unexpected expiry, set this higher than `session_lifetime`.

Despite the key name, this also affects server-side expiration of remembered login tokens. Clearing browser cookies removes remembered login on that browser, but does not itself revoke server-side remember tokens.

Defaults to `60*60*24*15` seconds (15 days).

### session_lifetime

    'session_lifetime' => 60 * 60 * 24,

Lifetime of authenticated sessions after inactivity, in seconds.

When "Remember me" is enabled, users may be transparently re-authenticated after session expiry/logout while the remember-login cookie remains valid.

To avoid earlier-than-expected remembered-login expiry, set `remember_login_cookie_lifetime` higher than this value.

Effective behavior also depends on related settings: - `session_keepalive` can extend active Web UI sessions via heartbeat requests. - `session_relaxed_expiry` may allow sessions to persist longer than this value. - `auto_logout` can enforce logout behavior in the Web UI.

The effective maximum retention also depends on PHP settings and external session-backend cleanup policies, including (but not limited to) PHP's `session.gc_maxlifetime` and environment-specific cleanup behavior (e.g., distro cron/tmpfiles policies and handler-specific GC behavior). These may override this value.

Defaults to `60*60*24` seconds (24 hours).

### davstorage.request_timeout

    'davstorage.request_timeout' => 30,

The timeout in seconds for requests to servers made by the DAV component (e.g., needed for federated shares).

### carddav_sync_request_timeout

    'carddav_sync_request_timeout' => 30,

The timeout in seconds for synchronizing address books, e.g., federated system address books (as run by `occ federation:sync-addressbooks`).

Defaults to `30` seconds

### carddav_sync_request_truncation

    'carddav_sync_request_truncation' => 2500,

The limit applied to the synchronization report request, e.g. federated system address books (as run by `occ federation:sync-addressbooks`).

### session_relaxed_expiry

    'session_relaxed_expiry' => false,

`true` enables a relaxed session timeout, where the session timeout would no longer be handled by Nextcloud but by either the PHP garbage collection or the expiration of potential other session backends like Redis.

This may lead to sessions being available for longer than what `session_lifetime` uses but comes with performance benefits as sessions are no longer a locking operation for concurrent requests.

### session_keepalive

    'session_keepalive' => true,

Enable or disable session keep-alive when a user is logged in to the Web UI.

Enabling this sends a "heartbeat" to the server to keep it from timing out.

Defaults to `true`

### auto_logout

    'auto_logout' => false,

Enable or disable the automatic logout after session_lifetime, even if session keepalive is enabled. This will make sure that an inactive browser will log itself out even if requests to the server might extend the session lifetime.

> **提示**
>
> The logout is handled on the client side. This is not a way to limit the duration of potentially compromised sessions.

Defaults to `false`

### token_auth_enforced

    'token_auth_enforced' => false,

Enforce token authentication for clients, which blocks requests using the user password for enhanced security. Users need to generate tokens in personal settings which can be used as passwords on their clients.

Defaults to `false`

### token_auth_activity_update

    'token_auth_activity_update' => 60,

The interval at which token activity should be updated.

Increasing this value means that the last activity on the security page gets more outdated.

Tokens are still checked every 5 minutes for validity max value: 300

Defaults to `60`

### auth.bruteforce.protection.enabled

    'auth.bruteforce.protection.enabled' => true,

Whether the brute force protection shipped with Nextcloud should be enabled or not.

> **注意**
>
> Disabling this is discouraged for security reasons.

Defaults to `true`

### auth.bruteforce.protection.force.database

    'auth.bruteforce.protection.force.database' => false,

Whether the brute force protection should write into the database even when a memory cache is available

Using the database is most likely worse for performance, but makes investigating issues a lot easier as it's possible to look directly at the table to see all logged remote addresses and actions.

Defaults to `false`

### auth.bruteforce.protection.testing

    'auth.bruteforce.protection.testing' => false,

Whether the brute force protection shipped with Nextcloud should be set to testing mode.

In testing mode, brute force attempts are still recorded, but the requests do not sleep/wait for the specified time. They will still abort with "429 Too Many Requests" when the maximum delay is reached. Enabling this is discouraged for security reasons and should only be done for debugging and on CI when running tests.

Defaults to `false`

### auth.bruteforce.max-attempts

    'auth.bruteforce.max-attempts' => 10,

Brute force protection: maximum number of attempts before blocking

When more than max-attempts login requests are sent to Nextcloud, requests will abort with "429 Too Many Requests". For security reasons, change it only if you know what you are doing.

Defaults to `10`

### ratelimit.protection.enabled

    'ratelimit.protection.enabled' => true,

Whether the rate limit protection shipped with Nextcloud should be enabled or not.

> **注意**
>
> Disabling this is discouraged for security reasons.

Defaults to `true`

### ratelimit_overwrite

    'ratelimit_overwrite' => [
            'profile.profilepage.index' => [
                'user' => ['limit' => 300, 'period' => 3600],
                'anon' => ['limit' => 1, 'period' => 300],
            ]
        ],

Overwrite the individual rate limit for a specific route

From time to time it can be necessary to extend the rate limit of a specific route, depending on your usage pattern or when you script some actions. Instead of completely disabling the rate limit or excluding an IP address from the rate limit, the following config allows to overwrite the rate limit duration and period.

The first level key is the name of the route. You can find the route name from a URL using the `occ router:list` command of your server.

You can also specify different limits for logged-in users with the `user` key and not-logged-in users with the `anon` key. However, if there is no specific `user` limit, the `anon` limit is also applied for logged-in users.

Defaults to empty array `[]`

### security.ipv6_normalized_subnet_size

    'security.ipv6_normalized_subnet_size' => 56,

Size of subnet used to normalize IPv6

For Brute Force Protection and Rate Limiting, IPv6 addresses are truncated using subnet size. It defaults to /56, but you can set it between /32 and /64

Defaults to `56`

### auth.webauthn.enabled

    'auth.webauthn.enabled' => true,

By default, WebAuthn is available, but it can be explicitly disabled by admins

### auth.storeCryptedPassword

    'auth.storeCryptedPassword' => true,

Whether encrypted passwords should be stored in the database

The passwords are only decrypted using the login token stored uniquely in the clients and allow connecting to external storages, autoconfiguring mail accounts in the mail app, and periodically checking if the password is still valid.

This might be desirable to disable this functionality when using one-time passwords or when having a password policy enforcing long passwords (\> 300 characters).

By default, the passwords are stored encrypted in the database.

> **注意**
>
> If disabled, password changes on the user backend (e.g., on LDAP) no longer log connected clients out automatically. Users can still disconnect the clients by deleting the app token from the security settings.

### hide_login_form

    'hide_login_form' => false,

By default, the login form is always available. There are cases (SSO) where an admin wants to avoid users entering their credentials to the system if the SSO app is unavailable.

This will show an error. But the direct login still works with adding `?direct=1`

### lost_password_link

    'lost_password_link' => 'https://example.org/link/to/password/reset',

If your user backend does not allow password resets (e.g., when it's a read-only user backend like LDAP), you can specify a custom link, where the user is redirected to, when clicking the "Reset password" link after a failed login attempt.

In case you do not want to provide any link, replace the URL with `'disabled'`

### logo_url

    'logo_url' => 'https://example.org',

URL to use as target for the logo link in the header (top-left logo)

Defaults to the base URL of your Nextcloud instance

## Mail Parameters

These configure the email settings for Nextcloud notifications and password resets.

### mail_domain

    'mail_domain' => 'example.com',

The return address that you want to appear on emails sent by the Nextcloud server, for example `nc-admin@example.com`, substituting your own domain, of course.

### mail_from_address

    'mail_from_address' => 'nextcloud',

FROM address that overrides the built-in `sharing-noreply` and `lostpassword-noreply` FROM addresses.

Defaults to different FROM addresses depending on the feature.

### mail_smtpdebug

    'mail_smtpdebug' => false,

Enable SMTP class debugging.

> **提示**
>
> `loglevel` will likely need to be adjusted too. See docs:  
> <https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/email_configuration.html#enabling-debug-mode>

Defaults to `false`

### mail_smtpmode

    'mail_smtpmode' => 'smtp',

Which mode to use for sending mail: `sendmail`, `smtp`, `qmail`, or `null`.

If you are using local or remote SMTP, set this to `smtp`.

For the `sendmail` option, you need an installed and working email system on the server, with `/usr/sbin/sendmail` installed on your Unix system.

For `qmail`, the binary is /var/qmail/bin/sendmail, and it must be installed on your Unix system.

Use the string `null` to send no mails (disable mail delivery). This can be useful if mails should be sent via APIs and rendering messages is not necessary.

Defaults to `smtp`

### mail_smtphost

    'mail_smtphost' => '127.0.0.1',

This depends on `mail_smtpmode`. Specify the IP address of your mail server host. This may contain multiple hosts separated by a semicolon. If you need to specify the port number, append it to the IP address separated by a colon, like this: `127.0.0.1:24`.

Defaults to `127.0.0.1`

### mail_smtpport

    'mail_smtpport' => 25,

This depends on `mail_smtpmode`. Specify the port for sending mail.

Defaults to `25`

### mail_smtptimeout

    'mail_smtptimeout' => 10,

This depends on `mail_smtpmode`. This sets the SMTP server timeout, in seconds. You may need to increase this if you are running an anti-malware or spam scanner.

Defaults to `10` seconds

### mail_smtpsecure

    'mail_smtpsecure' => '',

This depends on `mail_smtpmode`. Specify `ssl` when you are using SSL/TLS. Any other value will be ignored.

If the server advertises STARTTLS capabilities, they might be used, but they cannot be enforced by this config option.

Defaults to `''` (empty string)

### mail_smtpauth

    'mail_smtpauth' => false,

This depends on `mail_smtpmode`. Change this to `true` if your mail server requires authentication.

Defaults to `false`

### mail_smtpname

    'mail_smtpname' => '',

This depends on `mail_smtpauth`. Specify the username for authenticating to the SMTP server.

Defaults to `''` (empty string)

### mail_smtppassword

    'mail_smtppassword' => '',

This depends on `mail_smtpauth`. Specify the password for authenticating to the SMTP server.

Default to `''` (empty string)

### mail_template_class

    'mail_template_class' => '\OC\Mail\EMailTemplate',

Replaces the default mail template layout. This can be utilized if the options to modify the mail texts with the theming app are not enough.

The class must extend `\OC\Mail\EMailTemplate`

### mail_send_plaintext_only

    'mail_send_plaintext_only' => false,

Email will be sent by default with an HTML and a plain text body. This option allows sending only plain text emails.

### mail_smtpstreamoptions

    'mail_smtpstreamoptions' => [],

This depends on `mail_smtpmode`. Array of additional streams options that will be passed to underlying Swift mailer implementation.

Defaults to an empty array.

### mail_sendmailmode

    'mail_sendmailmode' => 'smtp',

Which mode is used for sendmail/qmail: `smtp` or `pipe`.

For `smtp`, the sendmail binary is started with the parameter `-bs`:  
- Use the SMTP protocol on standard input and output.

For `pipe`, the binary is started with the parameters `-t`:  
- Read message from STDIN and extract recipients.

Defaults to `smtp`

## Proxy Configurations

### overwritehost

    'overwritehost' => '',

The automatic hostname detection of Nextcloud can fail in certain reverse proxy and CLI/cron situations. This option allows you to manually override the automatic detection; for example, `www.example.com`, or specify the port `www.example.com:8080`.

### overwriteprotocol

    'overwriteprotocol' => '',

When generating URLs, Nextcloud attempts to detect whether the server is accessed via `https` or `http`. However, if Nextcloud is behind a proxy and the proxy handles the `https` calls, Nextcloud would not know that `ssl` is in use, which would result in incorrect URLs being generated.

Valid values are `http` and `https`.

### overwritewebroot

    'overwritewebroot' => '',

Nextcloud attempts to detect the webroot for generating URLs automatically.

For example, if `www.example.com/nextcloud` is the URL pointing to the Nextcloud instance, the webroot is `/nextcloud`. When proxies are in use, it may be difficult for Nextcloud to detect this parameter, resulting in invalid URLs.

### overwritecondaddr

    'overwritecondaddr' => '',

This option allows you to define a manual override condition as a regular expression for the remote IP address. For example, defining a range of IP addresses starting with `10.0.0.` and ending with 1 to 3: `^10\.0\.0\.[1-3]$`

Defaults to `''` (empty string)

### overwrite.cli.url

    'overwrite.cli.url' => '',

Set the canonical base URL Nextcloud should use when generating URLs outside a normal web request, such as in background jobs or at the command-line.

The value should be the full base URL including the web root, for example: `https://www.example.com/nextcloud`

In most setups, this should match the URL your users normally use to access Nextcloud. If it is incorrect, URL generation may be wrong in cron jobs, `occ`, notifications, and similar contexts.

> **提示**
>
> During installation, Nextcloud seeds this value from the installer’s current access context. If it was not preseeded (for example, via `autoconfig.php`), the inferred value may not match the public URL that users normally use to access Nextcloud and may need adjustment.

Defaults to `''` (empty string)

### htaccess.RewriteBase

    'htaccess.RewriteBase' => '/',

To have clean URLs without `/index.php`, this parameter needs to be configured.

This parameter will be written as "RewriteBase" on update and installation of Nextcloud to your `.htaccess` file. While this value is often simply the URL path of the Nextcloud installation, it cannot be set automatically properly in every scenario and needs thus some manual configuration.

In a standard Apache setup, this usually equals the folder that Nextcloud is accessible at. So if Nextcloud is accessible via `https://mycloud.org/nextcloud`, the correct value would most likely be `/nextcloud`. If Nextcloud is running under `https://mycloud.org/`, then it would be `/`.

Note that the above rule is not valid in every case, as there are some rare setup cases where this may not apply. However, to avoid any update problems, this configuration value is explicitly opt-in.

After setting this value, run `occ maintenance:update:htaccess`. Now, when the following conditions are met, Nextcloud URLs won't contain `index.php`:

- `mod_rewrite` is installed
- `mod_env` is installed

Defaults to `''` (empty string)

### htaccess.IgnoreFrontController

    'htaccess.IgnoreFrontController' => false,

For server setups that don't have `mod_env` enabled or restricted (e.g., suEXEC), this parameter has to be set to true and will assume mod_rewrite.

Please check if `mod_rewrite` is active and functional before setting this parameter, and you updated your .htaccess with `occ maintenance:update:htaccess`. Otherwise, your Nextcloud installation might not be reachable any more. For example, try accessing resources by leaving out `index.php` in the URL.

### proxy

    'proxy' => '',

The URL of your proxy server, for example, `proxy.example.com:8081`.

> **提示**
>
> Guzzle (the HTTP library used by Nextcloud) reads the environment variables `HTTP_PROXY` (only for CLI requests), `HTTPS_PROXY`, and `NO_PROXY` by default.

If you configure a proxy with Nextcloud, any default configuration by Guzzle is overwritten. Make sure to set `proxyexclude` accordingly if necessary.

Defaults to `''` (empty string)

### proxyuserpwd

    'proxyuserpwd' => '',

The optional authentication for the proxy to use to connect to the internet.

The format is: `username:password`.

Defaults to `''` (empty string)

### proxyexclude

    'proxyexclude' => [],

List of hostnames that should not be proxied to.

For example: `['.mit.edu', 'foo.com']`.

Hint: Use something like `explode(',', getenv('NO_PROXY'))` to sync this value with the global `NO_PROXY` option.

Defaults to empty array.

### allow_local_remote_servers

    'allow_local_remote_servers' => true,

Allow remote servers with local addresses, e.g., in federated shares, webcal services, and more

Defaults to `false`

### http_client_add_user_agent_url

    'http_client_add_user_agent_url' => false,

Add the URL of the Nextcloud server in User-Agent headers HTTP calls.

This helps service providers identifying calls from your server, which can be helpful for them, but can be a privacy issue on small Nextcloud servers.

Defaults to `false`

## Deleted Items (trash bin)

These parameters control the Deleted files app.

### trashbin_retention_obligation

    'trashbin_retention_obligation' => 'auto',

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. A file may be deleted after the minimum number of days has expired if space is needed. The file will not be deleted if space is not needed.

Whether "space is needed" depends on whether a user quota is defined or not:

> - If no user quota is defined, the available space on the Nextcloud data partition sets the limit for the trashbin (issues: see <https://github.com/nextcloud/server/issues/28451>).
> - If a user quota is defined, 50% of the user's remaining quota space sets the limit for the trashbin.

Maximum time is the number of days at which it is *guaranteed to be* deleted. There is no further dependency on the available space.

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.

Available values (D1 and D2 are configurable numbers):

- `auto`  
  Default setting. Keeps files and folders in the trash bin for at least **30** days.\
  Then, **if space is needed**, deletes trashed files anytime after that.

- `D1, auto`  
  Keeps files and folders in the trash bin for at least **D1** days.\
  Then, **if space is needed**, deletes trashed files anytime after that.

- `auto, D2`  
  **If space is needed**, deletes trashed files anytime.\
  After **D2** days, delete all trashed files automatically

- `D1, D2`  
  Keeps files and folders in the trash bin for at least **D1** days.\
  Then, after **D2** days, delete all trashed files automatically.

- `disabled`  
  Trash bin auto clean is disabled, files and folders will be kept forever.

Defaults to `auto`

## File versions

These parameters control the Versions app.

### versions_retention_obligation

    'versions_retention_obligation' => 'auto',

If the versions app is enabled (default), this setting defines the policy for when versions will be permanently deleted.

The app allows for two settings, a minimum time for version retention, and a maximum time for version retention. Minimum time is the number of days a version 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 version deletion. For migration purposes, this setting is installed initially set to "auto", which is equivalent to the default setting in Nextcloud.

Available values:

- `auto`  
  default setting. Automatically expire versions according to expire rules. Please refer to [Controlling file versions and aging](/link/971) for more information.

- `D, auto`  
  keep versions at least for D days, apply expiration rules to all versions that are older than D days

- `auto, D`  
  delete all versions that are older than D days automatically, delete other versions according to expire rules

- `D1, D2`  
  keep versions for at least D1 days and delete when exceeds D2 days

- `disabled`  
  versions auto clean disabled, versions will be kept forever

Defaults to `auto`

## Nextcloud Verifications

Nextcloud performs several verification checks. There are two options, `true` and `false`.

### appcodechecker

    'appcodechecker' => true,

Checks an app before install whether it uses private APIs instead of the proper public APIs. If this is set to true, it will only allow installing or enabling apps that pass this check.

Defaults to `false`

### updatechecker

    'updatechecker' => true,

Check if Nextcloud is up-to-date and shows a notification if a new version is available. It sends current version, PHP version, installation and last update time, and release channel to the updater server which responds with the latest available version based on those metrics.

Defaults to `true`

### integrity.check.scheduled

    'integrity.check.scheduled' => true,

Re-run the code integrity check once a day in a background job and notify admins when its result changes, for example when a file inside the Nextcloud or app folders is modified or added.

Defaults to `true`

### updater.server.url

    'updater.server.url' => 'https://updates.nextcloud.com/updater_server/',

URL that Nextcloud should use to look for updates

Defaults to `https://updates.nextcloud.com/updater_server/`

### updater.release.channel

    'updater.release.channel' => 'stable',

The channel that Nextcloud should use to look for updates

Supported values:

- `daily`
- `beta`
- `stable`

### has_internet_connection

    'has_internet_connection' => true,

Is Nextcloud connected to the Internet or running in a closed network?

Defaults to `true`

### connectivity_check_domains

    'connectivity_check_domains' => [
            'https://www.nextcloud.com',
            'https://www.startpage.com',
            'https://www.eff.org',
            'https://www.edri.org'
        ],

Which domains to request to determine the availability of an Internet connection. If none of these hosts are reachable, the administration panel will show a warning. Set to an empty list to not do any such checks (warning will still be shown).

If no protocol is provided, both http and https will be tested. For example, `http://www.nextcloud.com` and `https://www.nextcloud.com` will be tested for `www.nextcloud.com` If a protocol is provided, only this one will be tested.

Defaults to the following domains:

> - <https://www.nextcloud.com>
> - <https://www.startpage.com>
> - <https://www.eff.org>
> - <https://www.edri.org>

### check_for_working_wellknown_setup

    'check_for_working_wellknown_setup' => true,

Allows Nextcloud to verify a working .well-known URL redirects. This is done by attempting to make a request from JS to `https://example.tld/.well-known/caldav/`

Defaults to `true`

### check_for_working_htaccess

    'check_for_working_htaccess' => true,

This is a crucial security check on Apache servers that should always be set to `true`. This verifies that the `.htaccess` file is writable and works.

If it is not, then any options controlled by `.htaccess`, such as large file uploads, will not work. It also runs checks on the `data/` directory, which verifies that it can't be accessed directly through the Web server.

Defaults to `true`

### check_data_directory_permissions

    'check_data_directory_permissions' => true,

In rare setups (e.g., on OpenShift or Docker on Windows), the permissions check might block the installation while the underlying system offers no means to "correct" the permissions. In this case, set the value to false.

In regular cases, if issues with permissions are encountered, they should be adjusted accordingly. Changing the flag is discouraged.

Defaults to `true`

### config_is_read_only

    'config_is_read_only' => false,

In certain environments, it is desired to have a read-only configuration file.

When this switch is set to `true`, writing to the config file will be forbidden. Therefore, it will not be possible to configure all options via the Web interface. Furthermore, when updating Nextcloud, it is required to make the configuration file writable again and to set this switch to `false` for the update process.

Defaults to `false`

## Logging

### log_type

    'log_type' => 'file',

This parameter determines where the Nextcloud logs are sent.

- `file`: the logs are written to file `nextcloud.log` in the default Nextcloud data directory. The log file can be changed with parameter `logfile`.
- `syslog`: the logs are sent to the system log. This requires a syslog daemon to be active.
- `errorlog`: the logs are sent to the PHP `error_log` function.
- `systemd`: the logs are sent to the Systemd journal. This requires a system that runs Systemd and the Systemd journal. The PHP extension `systemd` must be installed and active.

Defaults to `file`

### log_type_audit

    'log_type_audit' => 'file',

This parameter determines where the audit logs are sent. See `log_type` for more information.

Defaults to `file`

### logfile

    'logfile' => '/var/log/nextcloud.log',

Name of the file to which the Nextcloud logs are written if parameter `log_type` is set to `file`.

Defaults to `[datadirectory]/nextcloud.log`

### logfile_audit

    'logfile_audit' => '/var/log/audit.log',

Name of the file to which the audit logs are written if parameter `log_type` is set to `file`.

Defaults to `[datadirectory]/audit.log`

### logfilemode

    'logfilemode' => 0640,

Log file mode for the Nextcloud logging type in octal notation.

Defaults to `0640` (writable by user, readable by group).

### loglevel

    'loglevel' => 2,

Loglevel to start logging at. Valid values are:

- `0` = Debug
- `1` = Info
- `2` = Warning
- `3` = Error
- `4` = Fatal.

Defaults to `2` (Warning)

### loglevel_frontend

    'loglevel_frontend' => 2,

Loglevel used by the frontend to start logging at. The same values as for `loglevel` can be used. If not set, it defaults to the value configured for `loglevel` or Warning if that is not set either.

Defaults to `2`

### loglevel_dirty_database_queries

    'loglevel_dirty_database_queries' => 0,

Loglevel used by the dirty database query detection. Useful to identify potential database bugs in production. Set this to loglevel or higher to see dirty queries in the logs.

Defaults to `0` (debug)

### syslog_tag

    'syslog_tag' => 'Nextcloud',

If you maintain different instances and aggregate the logs, you may want to distinguish between them. `syslog_tag` can be set per instance with a unique ID. Only available if `log_type` is set to `syslog` or `systemd`.

The default value is `Nextcloud`.

### syslog_tag_audit

    'syslog_tag_audit' => 'Nextcloud',

If you maintain different instances and aggregate the logs, you may want to distinguish between them. `syslog_tag_audit` can be set per instance with a unique ID. Only available if `log_type` is set to `syslog` or `systemd`.

The default value is the value of `syslog_tag`.

### log.condition

    'log.condition' => [
            'shared_secret' => '57b58edb6637fe3059b3595cf9c41b9',
            'users' => ['sample-user'],
            'apps' => ['files'],
            'matches' => [
                [
                    'shared_secret' => '57b58edb6637fe3059b3595cf9c41b9',
                    'users' => ['sample-user'],
                    'apps' => ['files'],
                    'loglevel' => 1,
                    'message' => 'contains substring'
                ],
            ],
        ],

Log condition for log level increase based on conditions. Once one of these conditions is met, the required log level is set to debug. This allows debugging specific requests, users, or apps

Supported conditions:  
- `shared_secret`: if a request parameter with the name log_secret is set to  
  this value, the condition is met

- `users`: if the current request is done by one of the specified users,  
  this condition is met

- `apps`: if the log message is invoked by one of the specified apps,  
  this condition is met

- `matches`: if all the conditions inside a group match,  
  this condition is met. This allows logging only entries to an app by a few users.

Defaults to an empty array.

### log.backtrace

    'log.backtrace' => false,

Enables logging a backtrace with each log line. Normally, only Exceptions carry backtrace information, which are logged automatically. This switch turns them on for any log message. Enabling this option will lead to increased log data size.

Defaults to `false`.

### logdateformat

    'logdateformat' => 'F d, Y H:i:s',

This uses PHP.date formatting; see <https://www.php.net/manual/en/function.date.php>

Defaults to ISO 8601 `2005-08-15T15:52:01+00:00`, see `\DateTime::ATOM` <https://www.php.net/manual/en/class.datetimeinterface.php#datetimeinterface.constants.atom>

### logtimezone

    'logtimezone' => 'Europe/Berlin',

The timezone for logfiles. See <https://www.php.net/manual/en/timezones.php>

Defaults to `UTC`

### log_query

    'log_query' => false,

Append all database queries and parameters to the log file. Use this only for debugging, as your logfile will become huge.

### log_rotate_size

    'log_rotate_size' => 100 * 1024 * 1024,

Enables log rotation and limits the total size of logfiles. Set it to 0 for no rotation. Specify a size in bytes, for example, 104857600 (100 megabytes = 100 \* 1024 \* 1024 bytes). A new logfile is created with a new name when the old logfile reaches your limit. If a rotated log file is already present, it will be overwritten.

Defaults to 100 MB

### profiler

    'profiler' => false,

Enable built-in profiler. Helpful when trying to debug performance issues.

Note that this has a performance impact and shouldn't be enabled on production.

### profiling.request

    'profiling.request' => false,

Enable profiling for individual requests if profiling single requests is enabled or the secret is passed.

This requires the excimer extension to be installed. Be careful with this, as it can generate a lot of data.

The profile data will be stored as a JSON file in the profiling.path directory that can be analyzed with speedscope.

Defaults to `false`

### profiling.request.rate

    'profiling.request.rate' => 0.001,

The rate at which profiling data is collected for individual requests.

A lower value means more data points but higher overhead.

Defaults to `0.001`

### profiling.secret

    'profiling.secret' => '',

A secret token that can be passed via ?profile_secret=\<secret\> to enable profiling for a specific request.

This allows profiling specific requests in production without enabling it globally.

No default value.

### profiling.sample

    'profiling.sample' => false,

Enable sampling-based profiling. This collects profiling data periodically rather than per-request.

This requires the excimer extension to be installed. Be careful with this, as it can generate a lot of data.

The profile data will be stored as a plain text file in the profiling.path directory that can be analyzed with speedscope.

Defaults to `false`

### profiling.sample.rate

    'profiling.sample.rate' => 1,

The rate at which sampling profiling data is collected in seconds.

A lower value means more frequent samples but higher overhead.

Defaults to `1`

### profiling.sample.rotation

    'profiling.sample.rotation' => 60,

How often (in minutes) the sample log files are rotated.

Defaults to `60`

### profiling.path

    'profiling.path' => '/tmp',

The directory where profiling data is stored.

Note that this directory must be writable by the web server user and will not be cleaned up automatically.

## Alternate Code Locations

Some Nextcloud code may be stored in alternate locations.

### customclient_desktop

    'customclient_desktop'
            => 'https://nextcloud.com/install/#install-clients',
        'customclient_android'
            => 'https://play.google.com/store/apps/details?id=com.nextcloud.client',
        'customclient_ios'
            => 'https://itunes.apple.com/us/app/nextcloud/id1125420102?mt=8',
        'customclient_ios_appid'
            => '1125420102',
        'customclient_fdroid'
            => 'https://f-droid.org/packages/com.nextcloud.client/',

This section is for configuring the download links for Nextcloud clients, as seen in the first-run wizard and on Personal pages.

Defaults to:

- Desktop client: `https://nextcloud.com/install/#install-clients`
- Android client: `https://play.google.com/store/apps/details?id=com.nextcloud.client`
- iOS client: `https://itunes.apple.com/us/app/nextcloud/id1125420102?mt=8`
- iOS client app ID: `1125420102`
- F-Droid client: `https://f-droid.org/packages/com.nextcloud.client/`

## Activity

Options for the activity app.

### activity_expire_days

    'activity_expire_days' => 365,

Retention of activities.

A daily cron job deletes all activities for all users which are older than the number of days specified here.

Defaults to `365`

### activity_use_cached_mountpoints

    'activity_use_cached_mountpoints' => false,

Activities in Team Folders and External Storages.

By default, activities in team folders or external storages are only generated for the current user. This is due to a limitations in current implementations. This config flag makes activities in group folders and external storages work like in normal shares (when set to `true`). Setting this flag does not allow past activities to be displayed (no retroactivity).

> **注意**
>
> Enabling this comes with some CRITICAL trade-offs:
>
> - If team folder "Advanced Permissions" (ACLs) are used, activities do not respect the permissions and therefore all users see all activities, even for files and directories they do not have access to.
> - Users who had access to a team folder, share, or external storage can see activities in their stream and emails that happen after they are removed until they log in again.
> - Users who are newly added to a team folder, share, or external storage cannot see activities in their stream or emails that happen after they are added until they log in again.

Defaults to `false`

## Apps

Options for the Apps folder, Apps store, and App code checker.

### defaultapp

    'defaultapp' => 'dashboard,files',

Set the default app to open on login. The entry IDs can be retrieved from the Navigations OCS API endpoint: <https://docs.nextcloud.com/server/latest/developer_manual/_static/openapi.html#/operations/core-navigation-get-apps-navigation>.

You can use a comma-separated list of app names, so if the first app is not enabled for a user, then Nextcloud will try the second one, and so on. If no enabled apps are found, it defaults to the dashboard app.

Defaults to `dashboard,files`

### appstoreenabled

    'appstoreenabled' => true,

When enabled, admins may install apps from the Nextcloud app store.

Defaults to `true`

### appstoreurl

    'appstoreurl' => 'https://apps.nextcloud.com/api/v1',

Enables the installation of apps from a self-hosted apps store.

Requires that at least one of the configured apps directories is writable.

Defaults to `https://apps.nextcloud.com/api/v1`

### appsallowlist

    'appsallowlist' => [],

Filters allowed installable apps from the appstore.

Empty array will prevent all apps from the store to be found.

### apps_paths

    'apps_paths' => [
            [
                'path' => '/var/www/nextcloud/apps',
                'url' => '/apps',
                'writable' => true,
            ],
        ],

Use the `apps_paths` parameter to set the location of the Apps directory, which should be scanned for available apps, and where user-specific apps should be installed from the Apps store. The `path` defines the absolute file system path to the app folder. The key `url` defines the HTTP Web path to that folder, starting from the Nextcloud webroot. The key `writable` indicates if a Web server can write files to that folder.

## Previews

Nextcloud supports generating previews for various file types, such as images, audio files, and text files. These options control enabling and disabling previews, and thumbnail size.

### enable_previews

    'enable_previews' => true,

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

- Image files
- Text documents

Valid values are `true`, to enable previews, or `false`, to disable previews

Defaults to `true`

### preview_concurrency_all

    'preview_concurrency_all' => 8,

Number of all preview requests being processed concurrently, including previews that need to be newly generated, and those that have been generated.

This should be greater than `preview_concurrency_new`. If unspecified, defaults to twice the value of `preview_concurrency_new`.

### preview_concurrency_new

    'preview_concurrency_new' => 4,

Number of new previews that are being concurrently generated.

Depending on the max preview size set by `preview_max_x` and `preview_max_y`, the generation process can consume considerable CPU and memory resources. It's recommended to limit this to be no greater than the number of CPU cores. If unspecified, defaults to the number of CPU cores, or 4 if that cannot be determined.

### preview_max_x

    'preview_max_x' => 4096,

The maximum width, in pixels, of a preview. A value of `null` means there is no limit.

Defaults to `4096`

### preview_max_y

    'preview_max_y' => 4096,

The maximum height, in pixels, of a preview. A value of `null` means there is no limit.

Defaults to `4096`

### preview_max_filesize_image

    'preview_max_filesize_image' => 50,

Max file size for generating image previews with imagegd (default behavior).

If the image is bigger, it'll try other preview generators, but will most likely either show the default mimetype icon or not display the image at all. Set to `-1` for no limit and try to generate image previews on all file sizes.

Defaults to `50` megabytes

### preview_max_memory

    'preview_max_memory' => 256,

Max memory for generating image previews with imagegd (default behavior) Reads the image dimensions from the header and assumes 32 bits per pixel.

If creating the image would allocate more memory, preview generation will be disabled and the default mimetype icon is shown. Set to `-1` for no limit.

Defaults to `256` megabytes

### preview_libreoffice_path

    'preview_libreoffice_path' => '/usr/bin/libreoffice',

Custom path for LibreOffice/OpenOffice binary

Defaults to `''` (empty string)

### preview_ffmpeg_path

    'preview_ffmpeg_path' => '/usr/bin/ffmpeg',

Custom path for ffmpeg binary

Defaults to `null` and falls back to searching `ffmpeg` in the configured `PATH` environment

### preview_ffprobe_path

    'preview_ffprobe_path' => '/usr/bin/ffprobe',

Custom path for ffprobe binary

Defaults to `null` and falls back to using the same path as ffmpeg. ffprobe is typically packaged with ffmpeg and is required for enhanced preview generation for HDR videos.

### preview_imaginary_url

    'preview_imaginary_url' => 'http://previews_hpb:8088/',

Set the URL of the Imaginary service to send image previews to.

Also requires the `OC\Preview\Imaginary` provider to be enabled in the `enabledPreviewProviders` array, to create previews for these mimetypes: bmp, x-bitmap, png, jpeg, gif, heic, heif, svg+xml, tiff, webp, and illustrator.

If you want Imaginary to also create preview images from PDF documents, you have to add the `OC\Preview\ImaginaryPDF` provider as well.

See <https://github.com/h2non/imaginary>

### preview_imaginary_key

    'preview_imaginary_key' => 'secret',

If you want to set an API key for Imaginary.

### enabledPreviewProviders

    'enabledPreviewProviders' => [
            'OC\Preview\PNG',
            'OC\Preview\JPEG',
            'OC\Preview\GIF',
            'OC\Preview\BMP',
            'OC\Preview\XBitmap',
            'OC\Preview\Krita',
            'OC\Preview\WebP',
            'OC\Preview\MarkDown',
            'OC\Preview\TXT',
            'OC\Preview\OpenDocument',
        ],

Only register providers that have been explicitly enabled

The following providers are disabled by default due to performance or privacy concerns:

> - `OC\Preview\EMF`
> - `OC\Preview\Font`
> - `OC\Preview\HEIC`
> - `OC\Preview\Illustrator`
> - `OC\Preview\Movie`
> - `OC\Preview\MP3`
> - `OC\Preview\MSOffice2003`
> - `OC\Preview\MSOffice2007`
> - `OC\Preview\MSOfficeDoc`
> - `OC\Preview\PDF`
> - `OC\Preview\Photoshop`
> - `OC\Preview\Postscript`
> - `OC\Preview\SGI`
> - `OC\Preview\StarOffice`
> - `OC\Preview\SVG`
> - `OC\Preview\TGA`
> - `OC\Preview\TIFF`

The following providers are disabled by default, because they provide an alternative to the built-in providers:  
- `OC\Preview\Imaginary`
- `OC\Preview\ImaginaryPDF`

Defaults to the following providers:

> - `OC\Preview\PNG`
> - `OC\Preview\JPEG`
> - `OC\Preview\GIF`
> - `OC\Preview\BMP`
> - `OC\Preview\XBitmap`
> - `OC\Preview\Krita`
> - `OC\Preview\WebP`
> - `OC\Preview\MarkDown`
> - `OC\Preview\TXT`
> - `OC\Preview\OpenDocument`

### metadata_max_filesize

    'metadata_max_filesize' => 256,

Maximum file size for file metadata generation.

Files larger than this limit will be skipped.

This limit helps bound resource usage during metadata generation. Actual resource usage depends on the active metadata providers and how they process files. As a rough guide, memory usage may scale with file size.

Default: 256 MiB.

### max_file_conversion_filesize

    'max_file_conversion_filesize' => 100,

Maximum file size for file conversion.

Files larger than this limit will be skipped.

Raising this limit may increase conversion time, resource usage, and the risk of timeouts or conversion failures depending on the provider.

Default: 100 MiB.

## LDAP

Global settings used by LDAP User and Group Backend

### ldapUserCleanupInterval

    'ldapUserCleanupInterval' => 51,

Defines the interval in minutes for the background job that checks user existence and marks them as ready to be cleaned up. The number is always minutes. Setting it to 0 disables the feature.

See command line (occ) methods `ldap:show-remnants` and `user:delete`

Defaults to `51` minutes

### sort_groups_by_name

    'sort_groups_by_name' => false,

Sort groups in the user settings by name instead of the user count

By enabling this, the user count beside the group name is disabled as well.

> *Deprecated since version 29.0.0:* Use the frontend instead or set the app config value `group.sortBy` for `core` to `2`

## Comments

Global settings for the Comments infrastructure

### comments.managerFactory

    'comments.managerFactory' => '\OC\Comments\ManagerFactory',

Replaces the default Comments Manager Factory. This can be utilized if an own or 3rd-party CommentsManager should be used that – for instance – uses the filesystem instead of the database to keep the comments.

Defaults to `\OC\Comments\ManagerFactory`

## Maintenance

These options are for halting user activity when you are performing server maintenance.

### maintenance

    'maintenance' => false,

Enable maintenance mode to disable Nextcloud

If you want to prevent users from logging in to Nextcloud before you start doing some maintenance work, you need to set the value of the maintenance parameter to true. Please keep in mind that users who are already logged in are kicked out of Nextcloud instantly.

Defaults to `false`

### maintenance_window_start

    'maintenance_window_start' => 1,

UTC Hour for maintenance windows

Some background jobs only run once a day. When an hour is defined for this config, the background jobs which advertise themselves as not time sensitive will be delayed during the "working" hours and only run in the 4 hours after the given time. This is, e.g., used for activity expiration, suspicious login training, and update checks.

A value of 1, e.g., will only run these background jobs between 01:00am UTC and 05:00am UTC.

Defaults to `100` which disables the feature

### ldap_log_file

    'ldap_log_file' => '',

Log all LDAP requests into a file

Warning: This heavily decreases the performance of the server and is only meant to debug/profile the LDAP interaction manually. Also, it might log sensitive data into a plain text file.

## SSL

### openssl

    'openssl' => [
            'config' => '/absolute/location/of/openssl.cnf',
        ],

Extra SSL options to be used for configuration.

Defaults to an empty array.

## Memory caching backend configuration

Available cache backends:

- `\OC\Memcache\APCu` APC user backend
- `\OC\Memcache\ArrayCache` In-memory array-based backend (not recommended)
- `\OC\Memcache\Memcached` Memcached backend
- `\OC\Memcache\Redis` Redis backend

Advice on choosing between the various backends:

- APCu should be easiest to install. Almost all distributions have packages. Use this for single user environment for all caches.
- Use Redis or Memcached for distributed environments. For the local cache (you can configure two) take APCu.

### memcache.local

    'memcache.local' => '\\OC\\Memcache\\APCu',

Memory caching backend for locally stored data

- Used for host-specific data, e.g., file paths

Defaults to `none`

### memcache.distributed

    'memcache.distributed' => '\\OC\\Memcache\\Memcached',

Memory caching backend for distributed data

- Used for installation-specific data, e.g., database caching
- If unset, defaults to the value of memcache.local

Defaults to `none`

### memcache_customprefix

    'memcache_customprefix' => 'mycustomprefix',

Cache Key Prefix for Redis or Memcached

- Used for avoiding collisions in the cache system
- May be used for ACL restrictions in Redis

Defaults to `''` (empty string)

### memcache.kvstore

    'memcache.kvstore' => [

Connection details for the Key-Value store used for in-memory caching, for example when using Valkey or Redis.

This is the brand-independent version of the `redis` and `redis.cluster` options below without depending on `php-redis` meaning no additional PHP extension needs to be installed. Redis and Valkey 4.0 up to 8.0 are supported, for SSL support Redis v6 or higher is required, Valkey 9 is supported but without support for numbered databased when using cluster mode.

Warning: If the cache server is not hosted on the same machine as Nextcloud, this can have a network overhead compared to the `php-redis` based backend below.

Three topologies are supported: a single server, a Sentinel managed replication set, and a server cluster. Configure exactly one of `server`, `sentinel` or `seeds`.

For enhanced security, it is recommended to configure ACLs in the cache server and configure the `user` and `password` (or a TLS client certificate). Alternatively, you can also configure the cache server to just use a `password`. See <https://valkey.io/topics/security/> for more information when using Valkey.

### server

    'server' => [
                'host' => 'localhost', // can also be a Unix domain socket: '/tmp/cache.sock'
                'port' => 6379, // ignored for Unix domain sockets
                // Protocol used to connect. One of 'tcp', 'tls' or 'unix'.
                // When omitted it is derived from the host (a leading '/' means 'unix').
                'protocol' => 'tcp',
            ],

Single server setup.

Also used as the connection template for the `sentinel` managed primary / replica connections.

## Sentinel managed replication setup.

Provide the name of the monitored service and one entry per Sentinel node. Each seed uses the same format as the `server` entry above. Uncomment to enable and remove the `server` / `seeds` entries.

### user

    //'seeds' => [
            //    ['host' => 'localhost', 'port' => 7000],
            //    ['host' => 'localhost', 'port' => 7001],
            //],

            // Optional: username, only sent when the cache server uses ACLs.
            'user' => '',
            // Optional: if not defined, no password will be used.
            'password' => '',
            // Optional: select a numbered database. Only supported for single
            // servers and Sentinel setups, clusters always use database 0.
            'dbindex' => 0,
            // Optional: connection timeout in seconds (float). 0 means no timeout.
            'timeout' => 0.0,
            // Optional: read/write timeout in seconds (float). 0 means no timeout.
            'read_timeout' => 0.0,
            // Optional: keep the connection open across requests. Defaults to false.
            'persistent' => false,
            // Optional: when the 'tls' protocol is used, provide the SSL context.
            // SSL context options, see https://www.php.net/manual/en/context.ssl.php
            //'ssl_context' => [
            //    'local_cert' => '/certs/cache.crt',
            //    'local_pk' => '/certs/cache.key',
            //    'cafile' => '/certs/ca.crt',
            //],
        ],

Cluster setup.

Provide some or all of the cluster nodes to bootstrap discovery. Each seed uses the same format as the `server` entry above. Uncomment to enable and remove the `server` / `sentinel` entries.

### redis

    'redis' => [
            'host' => 'localhost', // can also be a Unix domain socket: '/tmp/redis.sock'
            'port' => 6379,
            'timeout' => 0.0,
            'read_timeout' => 0.0,
            'user' => '', // Optional: if not defined, no password will be used.
            'password' => '', // Optional: if not defined, no password will be used.
            'dbindex' => 0, // Optional: if undefined, SELECT will not run and will use Redis Server's default DB Index.
            // If Redis in-transit encryption is enabled, provide certificates
            // SSL context https://www.php.net/manual/en/context.ssl.php
            'ssl_context' => [
                'local_cert' => '/certs/redis.crt',
                'local_pk' => '/certs/redis.key',
                'cafile' => '/certs/ca.crt'
            ]
        ],

Connection details for Redis to use for memory caching in a single server configuration.

For enhanced security, it is recommended to configure Redis to require a password. See <http://redis.io/topics/security> for more information.

We also support Redis SSL/TLS encryption as of version 6. See <https://redis.io/topics/encryption> for more information.

### redis.cluster

    'redis.cluster' => [
            'seeds' => [ // provide some or all of the cluster servers to bootstrap discovery, port required
                'localhost:7000',
                'localhost:7001',
            ],
            'timeout' => 0.0,
            'read_timeout' => 0.0,
            'failover_mode' => \RedisCluster::FAILOVER_ERROR,
            'user' => '', // Optional: if not defined, no password will be used.
            'password' => '', // Optional: if not defined, no password will be used.
            // If Redis in-transit encryption is enabled, provide certificates
            // SSL context https://www.php.net/manual/en/context.ssl.php
            'ssl_context' => [
                'local_cert' => '/certs/redis.crt',
                'local_pk' => '/certs/redis.key',
                'cafile' => '/certs/ca.crt'
            ]
        ],

Connection details for a Redis Cluster.

Redis Cluster support requires the PHP module phpredis in version 3.0.0 or higher.

Available failover modes:  
- `\RedisCluster::FAILOVER_NONE` - only send commands to master nodes (default)
- `\RedisCluster::FAILOVER_ERROR` - failover to slaves for read commands if master is unavailable (recommended)
- `\RedisCluster::FAILOVER_DISTRIBUTE` - randomly distribute read commands across master and slaves

> **注意**
>
> `\RedisCluster::FAILOVER_DISTRIBUTE` is a not recommended setting, and we strongly suggest to not use it if you use Redis for file locking. Due to the way Redis is synchronized, it could happen that the read for an existing lock is scheduled to a slave that is not fully synchronized with the connected master which then causes a FileLocked exception.

See <https://redis.io/topics/cluster-spec> for details about the Redis cluster

Authentication works with phpredis version 4.2.1+. See <https://github.com/phpredis/phpredis/commit/c5994f2a42b8a348af92d3acb4edff1328ad8ce1>

### memcached_servers

    'memcached_servers' => [
            // hostname, port and optional weight
            // or path and port 0 for Unix socket. Also see:
            // https://www.php.net/manual/en/memcached.addservers.php
            // https://www.php.net/manual/en/memcached.addserver.php
            ['localhost', 11211],
            //array('other.host.local', 11211),
        ],

Server details for one or more Memcached servers to use for memory caching.

### memcached_options

    'memcached_options' => [
            // Set timeouts to 50ms
            \Memcached::OPT_CONNECT_TIMEOUT => 50,
            \Memcached::OPT_RETRY_TIMEOUT => 50,
            \Memcached::OPT_SEND_TIMEOUT => 50,
            \Memcached::OPT_RECV_TIMEOUT => 50,
            \Memcached::OPT_POLL_TIMEOUT => 50,

            // Enable compression
            \Memcached::OPT_COMPRESSION => true,

            // Turn on consistent hashing
            \Memcached::OPT_LIBKETAMA_COMPATIBLE => true,

            // Enable Binary Protocol
            \Memcached::OPT_BINARY_PROTOCOL => true,

            // Binary serializer will be enabled if the igbinary PECL module is available
            //\Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_IGBINARY,
        ],

Connection options for Memcached

### cache_path

    'cache_path' => '',

Location of the cache folder, defaults to `data/$user/cache` where `$user` is the current user. When specified, the format will change to `$cache_path/$user` where `$cache_path` is the configured cache directory and `$user` is the user.

Defaults to `''` (empty string)

### cache_chunk_gc_ttl

    'cache_chunk_gc_ttl' => 60 * 60 * 24,

TTL of chunks located in the cache folder before they're removed by garbage collection (in seconds). Increase this value if users have issues uploading very large files via the Nextcloud Client as upload isn't completed within one day.

Defaults to `60*60*24` (1 day)

### cache_app_config

    'cache_app_config' => true,

Enable caching of the app config values.

If enabled the app config will be cached locally for a short TTL, reducing database load significantly on larger setups.

Defaults to `true`

## Using Object Store with Nextcloud

### objectstore

    'objectstore' => [
            'class' => 'OC\\Files\\ObjectStore\\Swift',
            'arguments' => [
                // trystack will use your Facebook ID as the username
                'username' => 'facebook100000123456789',
                // in the trystack dashboard, go to user -> settings -> API Password to
                // generate a password
                'password' => 'Secr3tPaSSWoRdt7',
                // must already exist in the objectstore, name can be different
                'container' => 'nextcloud',
                // prefix to prepend to the fileid, default is 'oid:urn:'
                'objectPrefix' => 'oid:urn:',
                // create the container if it does not exist. default is false
                'autocreate' => true,
                // required, dev-/trystack defaults to 'RegionOne'
                'region' => 'RegionOne',
                // The Identity / Keystone endpoint
                'url' => 'http://8.21.28.222:5000/v2.0',
                // uploadPartSize: size of the uploaded chunks, defaults to 524288000
                'uploadPartSize' => 524288000,
                // required on dev-/trystack
                'tenantName' => 'facebook100000123456789',
                // dev-/trystack uses swift by default, the lib defaults to 'cloudFiles'
                // if omitted
                'serviceName' => 'swift',
                // The Interface / URL Type, optional
                'urlType' => 'internal',
                // Maximum amount of data that can be uploaded
                'totalSizeLimit' => 1024 * 1024 * 1024,
            ],
        ],

This example shows how to configure Nextcloud to store all files in a Swift object storage.

It is important to note that Nextcloud in object store mode will expect exclusive access to the object store container because it only stores the binary data for each file. The metadata is currently kept in the local database for performance reasons.

> **注意**
>
> The current implementation is incompatible with any app that uses direct file I/O and circumvents our virtual filesystem. That includes Encryption and Gallery. Gallery will store thumbnails directly in the filesystem, and encryption will cause severe overhead because key files need to be fetched in addition to any requested file.

### objectstore

    'objectstore' => [
            'class' => 'OC\\Files\\ObjectStore\\Swift',
            'arguments' => [
                'autocreate' => true,
                'user' => [
                    'name' => 'swift',
                    'password' => 'swift',
                    'domain' => [
                        'name' => 'default',
                    ],
                ],
                'scope' => [
                    'project' => [
                        'name' => 'service',
                        'domain' => [
                            'name' => 'default',
                        ],
                    ],
                ],
                'tenantName' => 'service',
                'serviceName' => 'swift',
                'region' => 'regionOne',
                'url' => 'http://yourswifthost:5000/v3',
                'bucket' => 'nextcloud',
            ],
        ],

To use Swift V3

### objectstore

    'objectstore' => [
            'class' => 'OC\\Files\\ObjectStore\\S3',
            'arguments' => [
                'bucket' => 'nextcloud',
                'key' => 'your-access-key',
                'secret' => 'your-secret-key',
                'hostname' => 's3.example.com',
                'port' => 443,
                'use_ssl' => true,
                'region' => 'us-east-1',
                // optional: Maximum number of retry attempts for failed S3 requests
                // Default: 5
                'retriesMaxAttempts' => 5,
                // Data Integrity Protections for Amazon S3 (https://docs.aws.amazon.com/sdkref/latest/guide/feature-dataintegrity.html)
                // Valid values are "when_required" (default) and "when_supported".
                // To ensure compatibility with 3rd party S3 implementations, Nextcloud disables it by default. However, if you are
                // using Amazon S3 (or any other implementation that supports it) we recommend enabling it by using "when_supported".
                'request_checksum_calculation' => 'when_required',
                'response_checksum_validation' => 'when_required',
            ],
        ],

To use S3 object storage

### objectstore.multibucket.preview-distribution

    'objectstore.multibucket.preview-distribution' => false,

If this is set to true and a multibucket object store is configured, then newly created previews are put into 256 dedicated buckets.

Those buckets are named like the multibucket version but with the postfix `-preview-NUMBER` where NUMBER is between 0 and 255.

Keep in mind that only previews of files are put in there that don't have some already. Otherwise, the old bucket will be used.

To migrate existing previews to this new multibucket distribution of previews, use the occ command `preview:repair`. For now, this will only migrate previews that were generated before Nextcloud 19 in the flat `appdata_INSTANCEID/previews/FILEID` folder structure.

## Sharing

Global settings for Sharing

### sharing.managerFactory

    'sharing.managerFactory' => '\OC\Share20\ProviderFactory',

Replaces the default Share Provider Factory. This can be utilized if own or 3rd-party Share Providers are used that – for instance – use the filesystem instead of the database to keep the share information.

Defaults to `\OC\Share20\ProviderFactory`

### sharing.enable_mail_link_password_expiration

    'sharing.enable_mail_link_password_expiration' => false,

Enables expiration for link share passwords sent by email (sharebymail).

The passwords will expire after the configured interval; the users can still request a new one on the public link page.

### sharing.mail_link_password_expiration_interval

    'sharing.mail_link_password_expiration_interval' => 3600,

Expiration interval for passwords, in seconds.

### sharing.maxAutocompleteResults

    'sharing.maxAutocompleteResults' => 25,

Define max number of results returned by the search for auto-completion of users, groups, etc. The value must not be lower than 0 (for unlimited).

If more, different sources are requested (e.g., different user backends; or both users and groups), the value is applied per source and might not be truncated after collecting the results. I.e., more results can appear than configured here.

Default is 25.

### sharing.minSearchStringLength

    'sharing.minSearchStringLength' => 0,

Define the minimum length of the search string before we start auto-completion Default is no limit (value set to 0)

### sharing.enable_share_accept

    'sharing.enable_share_accept' => false,

Set to true to enable that internal shares need to be accepted by the users by default.

Users can change this for their account in their personal sharing settings

### sharing.force_share_accept

    'sharing.force_share_accept' => false,

Set to `true` to enforce that internal shares need to be accepted

### sharing.allow_custom_share_folder

    'sharing.allow_custom_share_folder' => true,

Set to `false` to prevent users from setting a custom share_folder

### share_folder

    'share_folder' => '/',

Define a default folder for shared files and folders other than root.

Changes to this value will only have effect on new shares.

Defaults to `/`

### sharing.enable_share_mail

    'sharing.enable_share_mail' => true,

Set to `false` to stop sending a mail when users receive a share

### sharing.allow_disabled_password_enforcement_groups

    'sharing.allow_disabled_password_enforcement_groups' => false,

Set to true to enable the feature to add exceptions for share password enforcement

### transferIncomingShares

    'transferIncomingShares' => false,

Set to true to always transfer incoming shares by default when running `occ files:transfer-ownership`.

Defaults to `false`, so incoming shares are not transferred if not specifically requested by a command line argument.

## Federated Cloud Sharing

### sharing.federation.allowSelfSignedCertificates

    'sharing.federation.allowSelfSignedCertificates' => false,

Allow self-signed certificates for federated shares

## Hashing

### hashing_default_password

    'hashing_default_password' => false,

By default, Nextcloud will use the Argon2 password hashing if available.

However, if for whatever reason you want to stick with the PASSWORD_DEFAULT of your PHP version, then set the setting to true.

Nextcloud uses the Argon2 algorithm (with PHP \>= 7.2) to create hashes by its own and exposes its configuration options as following. More information can be found at: <https://www.php.net/manual/en/function.password-hash.php>

### hashingThreads

    'hashingThreads' => PASSWORD_ARGON2_DEFAULT_THREADS,

The number of CPU threads to be used by the algorithm for computing a hash.

The value must be an integer, and the minimum value is `1`. Rationally, it does not help to provide a number higher than the available threads on the machine. Values that undershoot the minimum will be ignored in favor of the minimum.

### hashingMemoryCost

    'hashingMemoryCost' => PASSWORD_ARGON2_DEFAULT_MEMORY_COST,

The memory in KiB to be used by the algorithm for computing a hash. The value must be an integer, and the minimum value is 8 times the number of CPU threads.

Values that undershoot the minimum will be ignored in favor of the minimum.

### hashingTimeCost

    'hashingTimeCost' => PASSWORD_ARGON2_DEFAULT_TIME_COST,

The number of iterations that are used by the algorithm for computing a hash.

The value must be an integer, and the minimum value is `1`. Values that undershoot the minimum will be ignored in favor of the minimum.

### hashingCost

    'hashingCost' => 10,

The hashing cost used by hashes generated by Nextcloud Using a higher value requires more time and CPU power to calculate the hashes

## All other configuration options

### dbdriveroptions

    'dbdriveroptions' => [
            PDO::MYSQL_ATTR_SSL_CA => '/file/path/to/ca_cert.pem',
            PDO::MYSQL_ATTR_SSL_KEY => '/file/path/to/mysql-client-key.pem',
            PDO::MYSQL_ATTR_SSL_CERT => '/file/path/to/mysql-client-cert.pem',
            PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => false,
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET wait_timeout = 28800'
        ],

Additional driver options for the database connection, e.g., to enable SSL encryption in MySQL or specify a custom wait timeout on a cheap hoster.

When setting up TLS/SSL for encrypting the connections, you need to ensure that the passed keys and certificates are readable by the PHP process. In addition, `PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT` might need to be set to false, if the database server's certificate CN does not match with the hostname used to connect. The standard behavior here is different from the MySQL/MariaDB CLI client, which does not verify the server cert except `--ssl-verify-server-cert` is passed manually.

### sqlite.journal_mode

    'sqlite.journal_mode' => 'DELETE',

SQLite3 journal mode can be specified using this configuration parameter - can be `'WAL'` or `'DELETE'`. See <https://www.sqlite.org/wal.html> for more details.

### mysql.utf8mb4

    'mysql.utf8mb4' => false,

During setup, if requirements are met (see below), this setting is set to true to enable MySQL to handle 4-byte characters instead of 3-byte characters.

To convert an existing 3-byte setup to a 4-byte setup, configure the MySQL parameters as described below and run the migration command: `./occ db:convert-mysql-charset` This config setting will be automatically updated after a successful migration.

Refer to the documentation for more details.

MySQL requires specific settings for longer indexes (\> 767 bytes), which are necessary for 4-byte character support:

    [mysqld]
    innodb_large_prefix=ON
    innodb_file_format=Barracuda
    innodb_file_per_table=ON

Tables will be created with:  
- character set: `utf8mb4`
- collation: `utf8mb4_bin`
- row_format: `dynamic`

See:  
- <https://dev.mysql.com/doc/refman/5.7/en/charset-unicode-utf8mb4.html>
- <https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_large_prefix>
- <https://mariadb.com/kb/en/mariadb/xtradbinnodb-server-system-variables/#innodb_large_prefix>
- <http://www.tocker.ca/2013/10/31/benchmarking-innodb-page-compression-performance.html>
- <http://mechanics.flite.com/blog/2014/07/29/using-innodb-large-prefix-to-avoid-error-1071/>

### mysql.collation

    'mysql.collation' => null,

For search queries in the database, a default collation is chosen based on the character set. In some cases, a different collation is desired, such as for accent-sensitive searches.

MariaDB and MySQL share some collations, but also have incompatible ones, depending on the database server version.

This option allows overriding the automatic collation choice. Example:

    'mysql.collation' => 'utf8mb4_0900_as_ci',

This setting does not affect table creation or setup, where utf8\[mb4\]\_bin is always used. It applies only to SQL queries using LIKE comparison operators.

### pgsql_ssl

    'pgsql_ssl' => [
            'mode' => '',
            'cert' => '',
            'rootcert' => '',
            'key' => '',
            'crl' => '',
        ],

PostgreSQL SSL connection

### supportedDatabases

    'supportedDatabases' => [
            'sqlite',
            'mysql',
            'pgsql',
            'oci',
        ],

Database types supported for installation.

Available:  
- sqlite (SQLite3)
- mysql (MySQL)
- pgsql (PostgreSQL)
- oci (Oracle)

Defaults to:  
- sqlite (SQLite3)
- mysql (MySQL)
- pgsql (PostgreSQL)

### tempdirectory

    'tempdirectory' => '/tmp/nextcloudtemp',

Override the location where Nextcloud stores temporary files. Useful in setups where the system temporary directory is on a limited-space ramdisk, restricted, or when using external storage that does not support streaming.

The web server user/PHP must have write access to this directory. Ensure that PHP configuration recognizes this as a valid temporary directory by setting the TMP, TMPDIR, and TEMP environment variables accordingly. Additional permissions may be required for AppArmor or SELinux.

### updatedirectory

    'updatedirectory' => '',

Override the location where Nextcloud stores update files during updates.

Useful when the default `datadirectory` is on a network disk like NFS or is otherwise restricted. Defaults to the value of `datadirectory` if unset.

If set, the directory must be located outside the Nextcloud installation directory and writable by the web server user.

### forbidden_filenames

    'forbidden_filenames' => ['.htaccess'],

Block specific files or filenames, disallowing uploads or access (read and write).

`.htaccess` is blocked by default.

> **注意**
>
> Use this only if you understand the implications.

> **提示**
>
> This list is case-insensitive.

Defaults to `['.htaccess']`

### forbidden_filename_basenames

    'forbidden_filename_basenames' => [],

Disallow uploads of files with specific basenames. Matching existing files cannot be updated, and no new files can be created in matching folders.

The basename is the filename without the extension, e.g., for "archive.tar.gz", the basename is "archive".

> **提示**
>
> This list is case-insensitive.

Defaults to `[]` (empty array)

### forbidden_filename_characters

    'forbidden_filename_characters' => [],

Block specific characters in filenames. Useful for filesystems or operating systems (e.g., Windows) that do not support certain characters. Matching existing files cannot be updated, and no new files can be created in matching folders.

The `/` and `\` characters, as well as ASCII characters \[0-31\], are always forbidden.

Example for Windows: `['?', '<', '>', ':', '*', '|', '"']` See: <https://en.wikipedia.org/wiki/Comparison_of_file_systems#Limits>

Defaults to `[]` (empty array)

### forbidden_filename_extensions

    'forbidden_filename_extensions' => ['.part', '.filepart'],

Deny specific file extensions. Matching existing files cannot be updated, and no new files can be created in matching folders.

The `'.part'` extension is always forbidden, as it is used internally by Nextcloud.

Defaults to `['.filepart', '.part']`

### theme

    'theme' => '',

Specify the name of a theme to apply to Nextcloud. Themes are located in `nextcloud/themes/` by default.

Defaults to the theming app, included since Nextcloud 9.

### enforce_theme

    'enforce_theme' => '',

Enforce a specific user theme, disabling user theming settings. Must be a valid ITheme ID, e.g., `dark`, `dark-highcontrast`, `default`, `light`, `light-highcontrast`, `opendyslexic`.

### theming.standalone_window.enabled

    'theming.standalone_window.enabled' => true,

Enable or disable Progressive Web App (PWA) functionality, which allows browsers to open web applications in dedicated windows.

Defaults to `true`

### cipher

    'cipher' => 'AES-256-CTR',

Specify the default cipher for encrypting files. Supported ciphers:  
- AES-256-CTR
- AES-128-CTR
- AES-256-CFB
- AES-128-CFB

Defaults to `AES-256-CTR`

### encryption.use_legacy_base64_encoding

    'encryption.use_legacy_base64_encoding' => false,

Use the legacy base64 format for encrypted files instead of the more space-efficient binary format. This affects only newly written files; existing encrypted files remain readable regardless of the format.

Defaults to `false`

### minimum.supported.desktop.version

    'minimum.supported.desktop.version' => '3.3.50',

Specify the minimum Nextcloud desktop client version allowed to sync with this server. Connections from earlier clients will be denied. Defaults to the minimum officially supported version at the time of this server release.

Changing this may cause older, unsupported clients to malfunction, potentially leading to data loss or unexpected behavior.

Defaults to `3.3.50`

### maximum.supported.desktop.version

    'maximum.supported.desktop.version' => '99.99.99',

Specify the maximum Nextcloud desktop client version allowed to sync with this server. Connections from later clients will be denied.

Defaults to `99.99.99`

### localstorage.allowsymlinks

    'localstorage.allowsymlinks' => false,

Allow local storage to contain symlinks.

> **注意**
>
> Not recommended, as this allows Nextcloud to access files outside the data directory, posing a potential security risk.

Defaults to `false`

### localstorage.umask

    'localstorage.umask' => 0022,

Nextcloud overrides umask to ensure suitable access permissions regardless of web server or PHP-FPM configuration. Modifying this value has security implications and may cause issues with the installation.

Most installations should not modify this value.

Defaults to `0022`

### localstorage.unlink_on_truncate

    'localstorage.unlink_on_truncate' => false,

Allow storage systems that do not support modifying existing files to overcome this limitation by removing files before overwriting.

Defaults to `false`

### quota_include_external_storage

    'quota_include_external_storage' => false,

Include external storage mounts in quota calculations.

When enabled, user storage quotas will also include files stored on external storage mounts (such as SMB, SFTP, S3, etc.) that are configured for the user (either as personal or global/system mounts).

Only files visible to the user at these mount points are counted towards their quota. Files only visible to other users (on their own mounts) are not counted.

By default, system/global external storage mounts are shared: every user given access sees the same files and folders from the external storage. To have per-user isolation, configure the mount with user-specific path or credentials, or utilize a personal mount.

Enabling this option may impact performance if external storages are slow or unreliable.

Warning: This setting is considered EXPERIMENTAL and may not work with all external storage backends.

Defaults to `false`.

### external_storage.auth_availability_delay

    'external_storage.auth_availability_delay' => 1800,

When an external storage is unavailable (e.g., due to failed authentication), it is flagged as such for a specified duration. For authentication failures, this delay can be customized to reduce the likelihood of account lockouts in systems like Active Directory.

Defaults to `1800` seconds (30 minutes)

### files_external_allow_create_new_local

    'files_external_allow_create_new_local' => true,

Allow creation of external storages of type "Local" via the web interface and APIs. When disabled, local storages can still be created using the occ command:

    occ files_external:create /mountpoint local null::null -c datadir=/path/to/data

Defaults to `true`

### filesystem_check_changes

    'filesystem_check_changes' => 0,

Specify how often the local filesystem (Nextcloud data/ directory and NFS mounts in data/) is checked for changes made outside Nextcloud. This does not apply to external storage.

- `0` -\> Never check the filesystem for outside changes, improving performance when no external changes are expected.
- `1` -\> Check each file or folder at most once per request, recommended for general use if outside changes are possible.

Defaults to `0`

### part_file_in_storage

    'part_file_in_storage' => true,

Control where temporary ".part" files are written during direct (non-chunked) uploads.

While an upload is in progress, Nextcloud writes data to a temporary ".part" file and renames it to the final filename when the upload completes.

- true: create the temporary ".part" file in the destination storage/path. This typically avoids cross-storage moves and can improve reliability and performance on backends where rename within the same storage is cheap/atomic.
- false: create the temporary ".part" file in the user's root folder first. This may help with some external storages that have limited rename/move behavior, but can add extra copy/move overhead.

Note: This setting applies to direct (non-chunked) uploads only. Chunked/ resumable uploads use a separate uploads staging mechanism and are not controlled by this option.

Defaults to `true`.

### filesystem_cache_readonly

    'filesystem_cache_readonly' => false,

Read-only mode for scan/detection reconciliation writes to filecache.

When true, Nextcloud does not store filecache metadata changes that are identified through scanner/change-detection reconciliation paths (global: all storages).

Scope note:

- Nextcloud-originated operations (UI/WebDAV/clients) are generally handled through normal application write paths and thus will still update filecache even when this is set to true.
- Reconciliation/refresh paths are prevented from writing back discovered metadata deltas while this is enabled.

Practical effect:

- Changes made directly on storage outside Nextcloud are generally not reflected while enabled.
- Some metadata-dependent behavior can appear stale until this parameter is disabled (permitting reconciliation writes again).

Warning: This is an expert/global setting for specialized environments and is intentionally not default-safe for general deployments.

Defaults to `false`.

### trusted_proxies

    'trusted_proxies' => ['203.0.113.45', '198.51.100.128', '192.168.2.0/24'],

List of trusted proxy servers. Supported formats:

- IPv4 addresses, e.g., `192.168.2.123`
- IPv4 ranges in CIDR notation, e.g., `192.168.2.0/24`
- IPv6 addresses, e.g., `fd9e:21a7:a92c:2323::1`
- IPv6 ranges in CIDR notation, e.g., `2001:db8:85a3:8d3:1319:8a20::/95`

If a request's `REMOTE_ADDR` matches an address here, it is treated as a proxy, and the client IP is read from the HTTP header specified in `forwarded_for_headers` instead of `REMOTE_ADDR`.

Ensure `forwarded_for_headers` is configured if `trusted_proxies` is set.

Defaults to `[]` (empty array)

### forwarded_for_headers

    'forwarded_for_headers' => ['HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR'],

Headers trusted as containing the client IP address when used with `trusted_proxies`. For example, use `HTTP_X_FORWARDED_FOR` for the `X-Forwarded-For` header.

Incorrect configuration allows clients to spoof their IP address, bypassing access controls and rendering logs unreliable.

Defaults to `['HTTP_X_FORWARDED_FOR']`

### allowed_admin_ranges

    'allowed_admin_ranges' => ['192.0.2.42/32', '233.252.0.0/24', '2001:db8::13:37/64'],

List of trusted IP ranges for admin actions. If non-empty, all admin actions must originate from IPs within these ranges.

Supported formats: - IPv4 addresses or ranges, e.g., `192.0.2.42/32`, `233.252.0.0/24` - IPv6 addresses or ranges, e.g., `2001:db8::13:37/64`

Defaults to `[]` (empty array)

### allowed_no_password_confirmation_ranges

    'allowed_no_password_confirmation_ranges' => ['192.0.2.42/32', '233.252.0.0/24', '2001:db8::13:37/64'],

List of trusted IP ranges that can bypass password confirmation.

If non-empty, all endpoints marked with the PasswordConfirmationRequired attribute won't need a password confirmation when originating from IPs within these ranges.

Supported formats: - IPv4 addresses or ranges, e.g., `192.0.2.42/32`, `233.252.0.0/24` - IPv6 addresses or ranges, e.g., `2001:db8::13:37/64`

Defaults to `[]` (empty array)

### max_filesize_animated_gifs_public_sharing

    'max_filesize_animated_gifs_public_sharing' => 10,

Maximum file size (in megabytes) for animating GIFs on public sharing pages.

If a GIF exceeds this size, a static preview is shown.

Set to `-1` for no limit.

Defaults to `10` megabytes

### filelocking.ttl

    'filelocking.ttl' => 60 * 60,

Set the lock's time-to-live (TTL) in seconds. Locks older than this are automatically cleaned up.

Defaults to `3600` seconds (1 hour) or the PHP `max_execution_time`, whichever is higher.

### memcache.locking

    'memcache.locking' => '\\OC\\Memcache\\Redis',

Memory caching backend for file locking. Redis is highly recommended to avoid data loss, as many memcache backends may evict values unexpectedly.

Defaults to `none`

### filelocking.debug

    'filelocking.debug' => false,

Enable debug logging for file locking. This can generate a large volume of log entries, potentially causing performance degradation and large log files on busy instances.

Use with `log.condition` to limit logging in production environments.

Defaults to `false`

### upgrade.disable-web

    'upgrade.disable-web' => false,

Disable the web-based updater.

Defaults to `false`

### upgrade.cli-upgrade-link

    'upgrade.cli-upgrade-link' => '',

Customize the CLI upgrade documentation link.

### user_ini_additional_lines

    'user_ini_additional_lines' => '',

Additional line(s) (string or array of strings) that will be added to .user.ini on each update by the updater.

Defaults to `''` (empty string)

### documentation_url.server_logs

    'documentation_url.server_logs' => '',

Customize the server logs documentation link for exception handling.

### debug

    'debug' => false,

Enable debugging mode for Nextcloud. Only use for local development, not in production, as it disables minification and outputs additional debug information.

Defaults to `false`

### data-fingerprint

    'data-fingerprint' => '',

Set the data fingerprint for the current data served. Used by clients to detect if a backup has been restored. Update this by running:

    occ maintenance:data-fingerprint

Changing or deleting this value may cause connected clients to stall until conflicts are resolved.

Defaults to `''` (empty string)

### configfilemode

    'configfilemode' => 0640,

config.php file mode in octal notation.

Defaults to `0640` (writable by user, readable by group).

### copied_sample_config

    'copied_sample_config' => true,

This entry serves as a warning if the sample configuration was copied.

DO NOT ADD THIS TO YOUR CONFIGURATION!

Ensure all settings are modified only after consulting the documentation.

### lookup_server

    'lookup_server' => 'https://lookup.nextcloud.com',

Use a custom lookup server to publish user data.

Defaults to `https://lookup.nextcloud.com`

### gs.enabled

    'gs.enabled' => false,

Enable Nextcloud's Global Scale architecture.

Defaults to `false`

### gs.federation

    'gs.federation' => 'internal',

Configure federation for Global Scale setups. Set to `global` to allow federation outside the environment.

Defaults to `internal`

### csrf.optout

    'csrf.optout' => [
            '/^WebDAVFS/', // OS X Finder
            '/^Microsoft-WebDAV-MiniRedir/', // Windows WebDAV drive
        ],

List of user agents exempt from SameSite cookie protection due to non-standard HTTP behavior.

> **注意**
>
> Use only if you understand the implications.

Defaults to:

- `/^WebDAVFS/` (OS X Finder)
- `/^Microsoft-WebDAV-MiniRedir/` (Windows WebDAV drive)

### core.login_flow_v2.allowed_user_agents

    'core.login_flow_v2.allowed_user_agents' => [],

Specify allowed user agents for Login Flow V2 using regular expressions.

User agents not matching this list are denied access to Login Flow V2.

> **注意**
>
> Use only if you understand the implications.

Example: Allow only the Nextcloud Android app:

    'core.login_flow_v2.allowed_user_agents' => ['/Nextcloud-android/i'],

Defaults to `[]` (empty array)

### simpleSignUpLink.shown

    'simpleSignUpLink.shown' => true,

Show or hide the "simple sign up" link on public pages.

See: <https://nextcloud.com/signup/>

Defaults to `true`

### login_form_autocomplete

    'login_form_autocomplete' => true,

Enable or disable autocompletion for the login form. Disabling this prevents browsers from remembering login credentials, which may be required for compliance with certain security policies.

Defaults to `true`

### login_form_timeout

    'login_form_timeout' => 300,

Set a timeout (in seconds) for the login form. After this period, the form is reset to prevent password leaks on public devices if the user forgets to clear it.

A value of 0 disables the timeout.

Defaults to `300` seconds (5 minutes)

### no_unsupported_browser_warning

    'no_unsupported_browser_warning' => false,

Suppress warnings for outdated or unsupported browsers. When enabled, users can bypass the warning after reading it.

Set to `true` to disable the warning.

Defaults to `false`

### files_no_background_scan

    'files_no_background_scan' => false,

Disable background scanning of files. When enabled, a background job runs every 10 minutes to sync the filesystem and database for up to 500 users with unscanned files (size \< 0 in filecache).

Defaults to `false`

### query_log_file

    'query_log_file' => '',

Log all database queries to a file.

> **注意**
>
> This significantly reduces server performance and is intended only for debugging or profiling query interactions. Sensitive data may be logged in plain text.

### query_log_file_requestid

    'query_log_file_requestid' => '',

Prefix all queries with the request ID when set to yes.

Requires `query_log_file` to be set.

### query_log_file_parameters

    'query_log_file_parameters' => '',

Include all query parameters in the query log when set to yes.

Requires `query_log_file` to be set.

> **注意**
>
> This may log sensitive data in plain text.

### query_log_file_backtrace

    'query_log_file_backtrace' => '',

Include a backtrace in the query log when set to yes.

Requires `query_log_file` to be set.

### redis_log_file

    'redis_log_file' => '',

Log all Redis requests to a file.

> **注意**
>
> This significantly reduces server performance and is intended only for debugging or profiling Redis interactions. Sensitive data may be logged in plain text.

### diagnostics.logging

    'diagnostics.logging' => true,

Enable diagnostics event logging. Logs timings of common execution steps at debug level. Use with `log.condition` to enable conditionally in production.

Defaults to `true`

### diagnostics.logging.threshold

    'diagnostics.logging.threshold' => 0,

Limit diagnostics event logging to events longer than the specified threshold (in milliseconds). A value of 0 disables diagnostics event logging.

### profile.enabled

    'profile.enabled' => true,

Toggle availability of user profiles.

User profile pages contain information that can be shared with other users, such as full name, phone number, organization, role, and similar fields.

Profiles are enabled by default, and profile data may be used by other features (for example, the system address book).

Profile visibility is layered: what is shared depends on a combination of system-wide and account-level privacy controls, and each field's visibility can be configured.

When set to false, profile functionality is disabled instance-wide.

Note: This affects user account profiles, not the developer performance profiler.

Defaults to true

### account_manager.default_property_scope

    'account_manager.default_property_scope' => [],

Override default scopes for account data. Valid properties and scopes are defined in `OCP\Accounts\IAccountManager`. Values are merged with defaults from `OC\Accounts\AccountManager`.

Example: Set phone property to private scope: `[\OCP\Accounts\IAccountManager::PROPERTY_PHONE => \OCP\Accounts\IAccountManager::SCOPE_PRIVATE]`

### projects.enabled

    'projects.enabled' => false,

Enable the deprecated Projects feature, superseded by Related Resources since Nextcloud 25.

Defaults to `false`

### bulkupload.enabled

    'bulkupload.enabled' => true,

Enable the bulk upload feature.

Defaults to `true`

### reference_opengraph

    'reference_opengraph' => true,

Enable fetching Open Graph metadata from remote URLs.

Defaults to `true`

### unified_search.enabled

    'unified_search.enabled' => false,

Enable the legacy unified search.

Defaults to `false`

### enable_non-accessible_features

    'enable_non-accessible_features' => true,

Enable features that do not yet comply with accessibility standards.

Defaults to `true`

### binary_search_paths

    'binary_search_paths' => [
            '/usr/local/sbin',
            '/usr/local/bin',
            '/usr/sbin',
            '/usr/bin',
            '/sbin',
            '/bin',
            '/opt/bin',
        ],

Directories where Nextcloud searches for external binaries (e.g., LibreOffice, sendmail, ffmpeg).

Defaults to: - /usr/local/sbin - /usr/local/bin - /usr/sbin - /usr/bin - /sbin - /bin - /opt/bin

### files.chunked_upload.max_size

    'files.chunked_upload.max_size' => 100 * 1024 * 1024,

Maximum chunk size for chunked uploads (in bytes). Larger chunks increase throughput but yield diminishing returns above 100 MiB. Services like Cloudflare may limit to 100 MiB.

Defaults to `100 * 1024 * 1024` (100 MiB)

### files.chunked_upload.max_parallel_count

    'files.chunked_upload.max_parallel_count' => 5,

Maximum number of chunks uploaded in parallel during chunked uploads. Higher counts increase throughput but consume more server resources, with diminishing returns. Value must be a positive integer.

Defaults to `5`

### files.trash.delete

    'files.trash.delete' => true,

Allow users to manually delete files from their trashbin. Automated deletions (e.g., due to low quota) are unaffected.

Defaults to `true`

### enable_lazy_objects

    'enable_lazy_objects' => true,

Enable PHP 8.4 lazy objects for Dependency Injection to improve performance by avoiding instantiation of unused objects.

Defaults to `true`

### default_certificates_bundle_path

    'default_certificates_bundle_path' => \OC::$SERVERROOT . '/resources/config/ca-bundle.crt',

Change the default certificates bundle used for trusting certificates.

Nextcloud ships its own up-to-date certificates bundle, but in certain cases admins may wish to specify a different bundle, for example the one shipped by their distro.

Defaults to OC::\$SERVERROOT . '/resources/config/ca-bundle.crt'.

### openmetrics_skipped_classes

    'openmetrics_skipped_classes' => [
            'OC\OpenMetrics\Exporters\FilesByType',
            'OCA\Files_Sharing\OpenMetrics\SharesCount',
        ],

OpenMetrics skipped exporters Allows to skip some exporters in the OpenMetrics endpoint `/metrics`.

Default to `[]` (empty array)

### openmetrics_allowed_clients

    'openmetrics_allowed_clients' => [
            '192.168.0.0/16',
            'fe80::/10',
            '10.0.0.1',
        ],

OpenMetrics allowed client IP addresses Restricts the IP addresses able to make requests on the `/metrics` endpoint.

Keep this list as restrictive as possible as metrics can consume a lot of resources.

Default to `[127.0.0.0/16', '::1/128]` (allow loopback interface only)

### preview_expiration_days

    'preview_expiration_days' => 0,

Delete previews older than a certain number of days to reduce storage usage.

Less than one day is not allowed, so set it to 0 to disable the deletion.

Defaults to `0`.

### background_jobs_expiration_days

    'background_jobs_expiration_days' => 60,

Delete job runs older than a certain number of days.

Less than one day is not allowed.

Defaults to `60`.


# Activity app

The Activity app records and summarizes user-visible events across your Nextcloud instance and can notify users via the activity stream, email, and push notifications. It is shipped and enabled by default.

> **提示**
>
> The Activity app is designed for user notifications, not for compliance or auditing. Users can enable or disable activity tracking for their own account, so the activity stream is not a reliable audit trail. If you need a complete log of all actions on your instance, use the **admin_audit** app instead — see [Logging](/link/932).

![*The Activity admin settings page showing default notification preferences for new accounts.*](https://docs.cocobook.com/uploads/images/gallery/2026-10/activity-settings-admin.png)

The Activity admin settings page showing default notification preferences for new accounts.

## Configuring your Nextcloud for the Activity app

### Enabling email notifications

To send activity notification emails, a working [Email](/link/929) is required.

It is also recommended to configure the background job run mode to a system run mode (`System Cron` or `systemd`) as described in [Background jobs](/link/924). The `Ajax` and `Webcron` modes may delay or skip email delivery.

### Admin settings

As an administrator, you can:

- Enable or disable notification emails globally using the **Enable notification emails** checkbox in **Settings** \> **Administration** \> **Activity**.
- Configure the default notification preferences for new accounts. Existing users keep their personal settings. The defaults apply to accounts created after the change.

> **提示**
>
> The **Enable notification emails** toggle prevents **new** emails from being queued. It does not retroactively remove emails that are already waiting in the queue. Emails queued before the toggle was disabled will still be sent by the background job on its next run. To stop those emails immediately, truncate or clear the `oc_activity_mq` database table.

- Configure the maximum number of activities fully displayed in notification emails using the `mail_max_items` setting. Activities beyond this limit are summarised as *"and X more"* at the bottom of the email. The default is `200` and the maximum allowed value is `1000`. For example, to set it to `500`:

      occ config:app:set activity mail_max_items --value=500

## Configuration reference

The following `config.php` options control Activity app behavior.

| Option | Default | Description |
|----|----|----|
| `activity_expire_days` | `365` | Number of days to retain activity records. A daily background job deletes all activities older than this value. Minimum is `1` day. |
| `activity_use_cached_mountpoints` | `false` | When `true`, activities in team folders and external storages are generated for all users with access, not just the acting user. See [Activities in Team Folders or External Storages](/link/920) for details and caveats. |
| `activity_expire_exclude_users` | `[]` | An array of user IDs whose activity records are never deleted by the expiration job. See [Excluding users from activity expiration](/link/920). |

## Activities in Team Folders or External Storages

By default, activities in team folders or external storages are only generated for the current user. This is due to the underlying logic of these storage backends. The config flag `activity_use_cached_mountpoints` makes activities work like in normal shares when set to `true`.

    'activity_use_cached_mountpoints' => true,

> **警告**
>
> If "Advanced Permissions" (ACLs) are enabled in a team folder, activities do not respect those permissions. As a result, users may see activity entries for files and directories they cannot access. **This can leak sensitive information.** See [this issue](https://github.com/nextcloud/groupfolders/issues/1057) for more information.

> **注意**
>
> Users who previously had access to a team folder, share, or external storage can continue to see new activity entries in their stream and emails until they log in again after access is removed.

> **提示**
>
> Users who are newly added to a team folder, share, or external storage will not see new activity entries in their stream or emails until they log in again after access is granted.

## Excluding users from activity expiration

For certain users, it might make sense to never expire their activity data, for example administrators. Set the config value `activity_expire_exclude_users` in your `config.php`:

    'activity_expire_exclude_users' => [
      'admin',
      'group_admin',
      'second_admin'
    ]

For these users, their activity records will never be deleted from the database.

## Better scheduling of activity emails

In certain scenarios it makes sense to send the activity emails more regularly. For example, you may want to send the hourly emails always at the full hour, daily emails before people start to work in the morning, and weekly emails on Monday morning.

A console command is available to trigger sending those emails. This allows you to set up custom cron jobs with specific timing instead of relying on the Nextcloud background job:

    # crontab -u www-data -e
     0  *  *  *  *    php -f /var/www/nextcloud/occ activity:send-mails hourly
    30  7  *  *  *    php -f /var/www/nextcloud/occ activity:send-mails daily
    30  7  *  *  MON  php -f /var/www/nextcloud/occ activity:send-mails weekly

If you want to manually send out all queued activity emails, you can run `occ activity:send-mails` without any argument.

## Troubleshooting

### Users are not receiving notification emails

1.  Verify that email is configured correctly. Send a test email from **Settings** \> **Administration** \> **Basic settings**.
2.  Check that **Enable notification emails** is turned on in **Settings** \> **Administration** \> **Activity**.
3.  Verify that the user has email notifications enabled in their personal notification settings (**Settings** \> **Personal** \> **Notifications**).
4.  Ensure the background job is running. If you use `Cron`, check that the system cron job is executing `php -f /var/www/nextcloud/cron.php` regularly.
5.  Check the Nextcloud log (`data/nextcloud.log`) for mail-related errors.

### Activities are missing for shared files or team folders

By default, activities in team folders and external storages are only generated for the acting user. See [Activities in Team Folders or External Storages](/link/920) for how to enable activities for all users with access.

### Database growing large due to activity data

The Activity app stores all events in the database. On instances with many users or high file turnover, this can lead to significant database growth. To manage this:

- Set `activity_expire_days` to a lower value (e.g. `90` or `180`) to automatically clean up older records.
- Ensure the Nextcloud background job is running so that the daily expiration job executes.
- To assess current database usage, check the size of the `oc_activity` and `oc_activity_mq` tables directly.

### Emails are still being sent after disabling notification emails

The **Enable notification emails** toggle is checked when *queuing* new emails. The background job that actually delivers emails (`MailQueueHandler`) does not re-read the toggle before sending, so emails that were already in the queue when the toggle was turned off will still be delivered.

To stop those emails immediately, clear the `oc_activity_mq` table:

    DELETE FROM oc_activity_mq;

After clearing the table, no further queued activity emails will be sent until new ones are queued (which requires the toggle to be re-enabled).


# Administration privileges (Delegation)

## Introduction

Nextcloud has built-in functionality which permits administrators to delegate authority to others without granting them full administration privileges (and without making them a member of the `admin` group).

This administration privilege delegation functionality is supported by many shipped and ecosystem apps that have their own settings areas under *Administration settings*.

> **提示**
>
> If you're an app developer and would like administrators to be able to utilize this functionality for your app, you need to enable support for delegation of your settings (see the Developer Manual for specifics).

> **提示**
>
> Delegation of user management is possible, but you can also use [Group Administrators](/link/1010).

> **注意**
>
> Delegation of user management allow the delegated users to add themselves to groups receiving delegation of other settings. This can be used to escalate privileges.

## Usage

By default only members of the `admin` group can access *Administration settings*. You can create additional user groups (or use existing ones) and then grant these groups access to specific settings.

While logged in to an account that is a member of the `admin` group, go to *Administration settings* -\> *Administration privilege*. You will be presented with the list of settings pages and sections, including for any installed apps, that support delegation.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/admin-right.png)

By clicking on the combo box, you will be able to choose which groups are able to access the selected settings. You can revoke access at any time by removing the group from the selection (or, if you wish only to revoke access for an individual account, by removing that account from the configured group).

> **提示**
>
> Not every settings page or section supports delegation. This is either because delegating access to that particular settings page would enable privilege escalation (i.e. bypassing of the limited administration authority) or delegation has not yet been implemented for that specific settings page or app.


# Android Deep Link Handling

Deep linking in Android allows your application to be launched directly from a URL, making it easier for users to navigate to specific content within your app. Starting from Android 12, handling deep links requires additional configuration using an `assetlinks.json` file to ensure the app and the host domain are properly associated.

## Android 11 and Below

For Android 11 and below, deep linking is straightforward and does not require additional configuration beyond the usual manifest settings.

## Android 12 and Above

For Android 12 and above, an additional configuration step is required to verify the relationship between your app and the host domain using the `assetlinks.json` file.

### Creating assetlinks.json

Create a file named `assetlinks.json` and host it in the .well-known directory of your website (e.g., <https://www.cloud.example.com/.well-known/assetlinks.json>).

Example `assetlinks.json`:

    [
      {
        "relation": ["delegate_permission/common.handle_all_urls"],
        "target": {
          "namespace": "android_app",
          "package_name": "com.cloud.example.nextcloud",
          "sha256_cert_fingerprints": [
            "FB:00:95:22:F6:5E:25:80:22:61:B6:7B:10:A4:5F:D7:0E:61:00:31:97:6F:40:B2:8A:64:9E:15:2D:ED:03:73"
          ]
        }
      }
    ]

#### Nextcloud Configuration Limitation

Due to the additional requirement of hosting an `assetlinks.json` file for Android 12 and above, Nextcloud cannot configure the Android client for all different hosts. This is because each host needs its own `assetlinks.json` file to establish a verified relationship with the app, and Nextcloud cannot manage this file for every possible host domain.

# Antivirus scanner

You can configure your Nextcloud server to automatically run a virus scan on newly-uploaded files with the Antivirus app for Files. The Antivirus app for Files integrates the open source anti-virus engine [ClamAV](https://www.clamav.net/index.html) with Nextcloud. ClamAV detects all forms of malware including Trojan horses, viruses, and worms, and it operates on all major file types including Windows, Linux, and Mac files, compressed files, executables, image files, Flash, PDF, and many others. ClamAV's Freshclam daemon automatically updates its malware signature database at scheduled intervals.

ClamAV runs on Linux and any Unix-type operating system, and Microsoft Windows. However, it has only been tested with Nextcloud on Linux, so these instructions are for Linux systems. You must first install ClamAV, and then install and configure the Antivirus app for Files on Nextcloud.

## Installing ClamAV

As always, the various Linux distributions manage installing and configuring ClamAV in different ways.

Debian, Ubuntu, Linux Mint  
On Debian and Ubuntu systems, and their many variants, install ClamAV with these commands:

    apt-get install clamav clamav-daemon

The installer automatically creates default configuration files and launches the `clamd` and `freshclam` daemons. You don't have to do anything more, though it's a good idea to review the ClamAV documentation and your settings in `/etc/clamav/`. Enable verbose logging in both `clamd.conf` and `freshclam.conf` until you get any kinks worked out.

RedHat Enterprise Linux 7, CentOS 7  
On RedHat Enterprise Linux 7 and related systems you must install the Extra Packages for Enterprise Linux (EPEL) repository, and then install ClamAV:

    yum install epel-release
    yum install clamav clamav-scanner clamav-scanner-systemd clamav-server
    clamav-server-systemd clamav-update

This installs two configuration files: `/etc/freshclam.conf` and `/etc/clamd.d/scan.conf`. You must edit both of these before you can run ClamAV. Both files are well-commented, and `man clamd.conf` and `man freshclam.conf` explain all the options. Refer to `/etc/passwd` and `/etc/group` when you need to verify the ClamAV user and group.

First edit `/etc/freshclam.conf` and configure your options. `freshclam` updates your malware database, so you want it to run frequently to get updated malware signatures. Run it manually post-installation to download your first set of malware signatures:

    freshclam

The EPEL packages do not include an init file for `freshclam`, so the quick and easy way to set it up for regular checks is with a cron job. This example runs it every hour at 47 minutes past the hour:

    # m   h  dom mon dow  command
      47  *  *   *    *  /usr/bin/freshclam --quiet

Please avoid any multiples of 10, because those are when the ClamAV servers are hit the hardest for updates.

Next, edit `/etc/clamd.d/scan.conf`. When you're finished you must enable the `clamd` service file and start `clamd`:

    systemctl enable clamd@scan.service
    systemctl start clamd@scan.service

That should take care of everything. Enable verbose logging in `scan.conf` and `freshclam.conf` until it is running the way you want.

Docker, Docker-compose  
To install ClamAV via docker or docker compose you can take official image of ClamAV, or build one by yourself. This example is based on docker image from <https://github.com/Cisco-Talos/clamav>.

You can mount ClamAV Socket from the Docker Container to the host System as volume. In this case you do not need to expose any port outside of container.

For a Docker run this command:

    docker run --name clamav -d -v /var/run/clamav/:/var/run/clamav/ -v /var/docker/clamav/virus_db/:/var/lib/clamav/ clamav/clamav:stable_base

For a Docker-compose use following settings:

    version: "3.6"
    services:
      clamav:
        image: "clamav/clamav:stable_base"
        container_name: "clamav"
        volumes:
          # Socket
          - /var/run/clamav/:/var/run/clamav/
          # Virus DB
          - /var/docker/clamav/virus_db/:/var/lib/clamav/
        restart: unless-stopped

## Enabling the antivirus app for files

Place the `files_antivirus` app into the `apps` directory of your Nextcloud server. Then the app shows up on the Nextcloud Apps page where it simply can be enabled.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/antivirus-app.png)

## Configuring ClamAV on Nextcloud

Next, go to your Nextcloud Admin page and set your Nextcloud logging level to Everything.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/antivirus-logging.png)

Now find your Antivirus Configuration panel on your Admin page.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/antivirus-config.png)

ClamAV runs in one of three modes:

- Daemon (Socket): ClamAV is running on the same server as Nextcloud. The ClamAV daemon, `clamd`, runs in the background. When there is no activity `clamd` places a minimal load on your system. If your users upload large volumes of files you will see high CPU usage.
- Daemon: ClamAV is running on a different server. This is a good option for Nextcloud servers with high volumes of file uploads.
- Executable: ClamAV is running on the same server as Nextcloud, and the `clamscan` command is started and then stopped with each file upload. `clamscan` is slow and not always reliable for on-demand usage; it is better to use one of the daemon modes.

Daemon (Socket)  
Nextcloud should detect your `clamd` socket and fill in the `Socket` field. This is the `LocalSocket` option in `clamd.conf`. You can run `netstat` to verify:

    netstat -a|grep clam
    unix 2 [ ACC ] STREAM LISTENING 15857 /var/run/clamav/clamd.ctl

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/antivirus-daemon-socket.png)

The `Stream Length` value sets the number of bytes read in one pass. 26214400 bytes, or 25 MiB, is the default. This value should be no larger than the PHP `memory_limit` settings, or physical memory if `memory_limit` is set to -1 (no limit).

`Action for infected files found while scanning` gives you the choice of logging any alerts without deleting the files, or immediately deleting infected files.

Daemon  
For the Daemon option you need the hostname or IP address of the remote server running ClamAV, and the server's port number.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/antivirus-daemon.png)

Executable  
The Executable option requires the path to `clamscan`, which is the interactive ClamAV scanning command. Nextcloud should find it automatically.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/antivirus-executable.png)

When you are satisfied with how ClamAV is operating, you might want to go back and change all of your logging to less verbose levels.

## Confirm everything is working

Every antivirus provider implements a test virus string, that way tests are quite easy. You find the files here: <https://www.eicar.org/download-anti-malware-testfile/>

Uploading the file will trigger an error:  
"Virus Win.Test.EICAR_HDB-1 is detected in the file. Upload cannot be completed."

## Encrypted File Detection Limitations with ClamAV

By default, ClamAV may still return "OK" for password-protected archives and encrypted files. This known ClamAV behavior bypasses "Block unscannable files" option of Antivirus app. You may configure additional alert options in `clamd.conf`, that should catch it:

- `AlertEncryptedArchive` - Alert on encrypted archives with heuristic signature (encrypted .zip, .7zip, .rar).
- `AlertEncryptedDoc` - Alert on encrypted archives with heuristic signature (encrypted .pdf).
- `AlertEncrypted` - Alert on both encrypted archives and documents with heuristic signature.

For reliable detection and blocking of encrypted files, consult available antivirus backends documentation.

## Manage the background scanner

The background scanner does not require any manual intervention. However at times you might want to inspect it or perform tasks on it.

### How the background scanner works

Each time the background scanner runs, it processes files in three passes (in priority order), up to the configured batch size per run:

1.  **Unscanned files** — files that have never been scanned, including files that were uploaded or existed before the Antivirus app was installed. All such files will eventually be scanned as the background job runs repeatedly.
2.  **Modified files** — files whose modification time is newer than their last scan time, i.e. files that have been updated since they were last scanned.
3.  **Outdated files** — files that were last scanned more than 28 days ago (configurable via `av_rescan_days`), to account for updated virus definitions.

The scanner runs at most once every 15 minutes by default. The effective frequency is also bounded by how often Nextcloud's background job mechanism (cron, webcron, or ajax) runs.

To change the minimum interval between runs (in seconds):

    sudo -E -u www-data php occ config:app:set files_antivirus av_scan_interval --value="900"

To change the number of days before already-scanned files are rescanned:

    sudo -E -u www-data php occ config:app:set files_antivirus av_rescan_days --value="28"

**External storage:** files on external storage are included in passes 1 and 2 (initial scan and rescan on modification). However, the periodic 28-day rescan (pass 3) applies only to files under `files/` (i.e. home storage), not external storage.

### Get info about files in the scan queue

    sudo -E -u www-data php occ files_antivirus:status [-v]

### Manually trigger the background scan

    sudo -E -u www-data php occ files_antivirus:background-scan [-v] [-m MAX]

### Manually scan a single file

    sudo -E -u www-data php occ files_antivirus:scan <path>

### Mark a file as scanned or unscanned

    sudo -E -u www-data php occ files_antivirus:mark <path> <scanned|unscanned>

Files marked as scanned will not be scanned for the next four weeks.

## Configuring ICAP on Nextcloud

Nextcloud offers the integration of antivirus protection based on the ICAP protocol. The settings are outlined here. Additional documentation is work in progress.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/antivirus-icap.png)

## Disabling background scan task

You can disable background scan with occ to only scan files during upload:

    sudo -E -u www-data php occ config:app:set files_antivirus av_background_scan --value="off"

> **提示**
>
> Setting `av_rescan_days` to `0` does **not** disable the periodic rescan of already-scanned files. Any value below `1` is silently replaced with the default of 28 days, so the rescan continues on its normal schedule. Use `av_background_scan` as shown above to stop background scanning altogether.


# Background jobs

A system like Nextcloud sometimes requires tasks to be done on a regular basis without the need for user interaction or hindering Nextcloud performance. For that purpose, as a system administrator, you can define background jobs (for example, database clean-ups) which are executed without any need for user interaction.

These jobs are typically referred to as *cron jobs*. Cron jobs are commands or shell-based scripts that are scheduled to run periodically at fixed times, dates, or intervals. `cron.php` is a Nextcloud internal process that runs such background jobs on demand.

Nextcloud apps register actions with `cron.php` automatically to take care of typical housekeeping operations, such as garbage collecting of temporary files or checking for newly updated files using `filescan()` for externally mounted file systems.

## Parameters

### `maintenance_window_start`

> **提示**
>
> This setting is only taken into account in `cron` mode.

In the `config/config.php` file you can specify this config. Some background jobs only run once a day. When an hour is defined (timezone is UTC) for this config, the background jobs which advertise themselves as not time-sensitive will be delayed during the "working" hours and only run in the 4 hours after the given time. This is e.g. used for activity expiration, suspicious login training, and update checks.

A value of 1 e.g. will only run these background jobs between 01:00am UTC and 05:00am UTC:

    'maintenance_window_start' => 1,

If you don't care when these jobs run, you can set the value to `100`, but beware that resource intensive jobs may then run unnecessarily during high usage periods. This may lead to slower performance and a lower quality user experience.

This setting may also be set directly via `occ` just like any other configuration parameter:

    occ config:system:set maintenance_window_start --type=integer --value=1

## Cron jobs

You can schedule cron jobs in three ways -- using AJAX, Webcron, or cron. The default method is to use AJAX. However, the recommended method is to use cron. The following sections describe the differences between each method.

### AJAX

**Use case: Single user instance**

The AJAX scheduling method is the default option. Unfortunately, however, it is also the least reliable. Each time a user visits the Nextcloud page, a single background job is executed. The advantage of this mechanism is that it does not require access to the system nor registration with a third-party service. The disadvantage of this mechanism, when compared to the Webcron service, is that it requires regular visits to the page for it to be triggered.

> **注意**
>
> Especially when using the Activity app or external storages, where new files are added, updated or deleted, or when **multiple users** use the server, it is recommended to use `cron`.

### Webcron

**Use case: Very small instance** (1–5 users depending on the usage)

By registering your Nextcloud `cron.php` script address at an external webcron service (for example, [easyCron](https://www.easycron.com/)), you ensure that background jobs are executed regularly. To use this type of service with your server, you must be able to access your server using the Internet. For example:

    URL to call: http[s]://<domain-of-your-server>/nextcloud/cron.php

> **注意**
>
> Since WebCron is still executed via the web, the webserver in most cases limits the resources on the execution. To avoid interrupts inside jobs only 1 job is executed per call. When webcron is called once every 5 minutes this limits your instance to 288 background jobs per day, which is only suitable for very small instances. For bigger instances, it is recommended to use `cron`.

### Cron

Using the operating system cron feature is the preferred method for executing regular tasks. This method enables the execution of scheduled jobs without the inherent limitations the Web server might have.

To run a cron job on a \*nix system, every 5 minutes, under the default Web server user (often, `www-data` or `wwwrun`), you must set up the following cron job to call the **cron.php** script:

    # crontab -u www-data -e

And append this line:

    */5  *  *  *  * php -f /var/www/nextcloud/cron.php

You can verify if the cron job has been added and scheduled by executing:

    # crontab -u www-data -l

Which returns:

    [snip]
    */5  *  *  *  * php -f /var/www/nextcloud/cron.php

> **提示**
>
> You have to replace the path `/var/www/nextcloud/cron.php` with the path to your current Nextcloud installation.

> **提示**
>
> On some systems it might be required to call **php-cli** instead of **php**.

> **提示**
>
> Please refer to the crontab man page for the exact command syntax.

### systemd

If systemd is installed on the system, a systemd timer could be an alternative to a cronjob.

This approach requires two files: **nextcloudcron.service** and **nextcloudcron.timer**. Create these two files in `/etc/systemd/system/`.

**nextcloudcron.service** should look like this:

    [Unit]
    Description=Nextcloud cron.php job

    [Service]
    User=www-data
    ExecCondition=php -f /var/www/nextcloud/occ status -e
    ExecStart=/usr/bin/php -f /var/www/nextcloud/cron.php
    KillMode=process

Replace the user `www-data` with the user of your http server and `/var/www/nextcloud/cron.php` with the location of **cron.php** in your nextcloud directory.

The ExecCondition checks that the nextcloud instance is operating normally before running the background job, and skips it if otherwise.

The `KillMode=process` setting is necessary for external programs that are started by the cron job to keep running after the cron job has finished.

Note that the **.service** unit file does not need an `[Install]` section. Please check your setup because we recommended it in earlier versions of this admin manual.

**nextcloudcron.timer** should look like this:

    [Unit]
    Description=Run Nextcloud cron.php every 5 minutes

    [Timer]
    OnBootSec=5min
    OnUnitActiveSec=5min
    Unit=nextcloudcron.service

    [Install]
    WantedBy=timers.target

The important parts in the timer-unit are `OnBootSec` and `OnUnitActiveSec`. `OnBootSec` will start the timer 5 minutes after boot, otherwise, you would have to start it manually after every boot. `OnUnitActiveSec` will set a 5-minute timer after the service-unit was last activated.

Now all that is left is to start and enable the timer by running this command:

    systemctl enable --now nextcloudcron.timer

When the option `--now` is used with `enable`, the respective unit will also be started.

> **提示**
>
> Selecting the option `Cron` in the admin menu for background jobs is not mandatory, because once cron.php is executed from the command line or cron service it will set it automatically to `Cron`.

# Brute force protection

## Introduction

Nextcloud has built-in protection against brute force attempts.

The brute force protection feature is meant to protect Nextcloud servers from attempts to guess passwords and tokens in various ways. Besides the obvious "let's try a big list of commonly used passwords" attack, it also makes it harder to use slightly more sophisticated attacks via the reset password page or trying to find app password tokens. It is used throughout the Nextcloud ecosystem, including by other apps, if they have sensitive entrypoints (and choose to enable support for it).

## How it works

### Overview

If triggered, brute force protection makes requests - coming from an IP address via a brute force protected entrypoint - slower for up to a 24 hour period. In extreme circumstances it may prevent access outright, for up to 30 minutes, from a problematic IP address.

This protects your system from attackers trying, for example, a lot of different passwords.

The primary filter is IP address-based. This means that any account - even one associated with a given brute force attempt - is not impacted when it is connecting from a different IP address than any brute force attempts. This helps minimize inadvertent denial of service attacks against legitimate connections, while maximizing attack resistance from problematic IP sources.

Nuisance triggers are minimized through reasonable built-in defaults appropriate to each type of action.

The attempts history is automatically managed by a daily cronjob. Individual entries expire after 48 hours (attempts, however, may be still *logged* indefinitely elsewhere through the usual mechanisms within Nextcloud Server and at the discretion of the admin).

Excluding (whitelisting) select IP addresses from brute force protection to prevent false positives is supported, but usually false positives are best handled by fixing the underlying causes (e.g. a misconfigured reverse proxy or misbehaving client).

> **提示**
>
> If you do notice a problem with the authentication behavior of any the official Nextcloud clients, please report it to the appropriate repository so that it can be looked into.

Keeping brute force protection active and operating properly helps protects your Nextcloud Server from malicious actors while minimizing potential impact on legitimate usage.

### Example: The login page

The brute force protection is easiest to see in action on the login page. If you try to log in the first time with an invalid username and/or password you will not notice anything. But if you do this a few times you start to notice that the verification of the login is taking longer each time. This is the brute force protection kicking in.

The maximum delay is 25 seconds, unless maximum number of attempts (currently 10) was reached within the last 30 minutes (in which case a `429 Too Many Requests` will be returned until the maximum attempts within the recent time has dropped below the threshold).

After a successful login (from the same source IP address), any prior invalid login attempts will be cleared and you will no longer be hit by the delay.

> **提示**
>
> Not all actions are necessarily viewed the same. It is possible for some activities to be more (or less) strict than others.

## Usage

### Activating

Brute force protection is enabled by default on Nextcloud. Its behavior can be adjusted through the `bruteforcesettings` app (shipped with Server and enabled by default), several `occ` commands, and several `config.php` parameters. Its effectiveness is highly dependent on having a properly configured environment, particularly when integrating a reverse proxy with Nextcloud (and associated parameters such as `trusted_proxies`).

### The brute force settings app

This app, which shipped and enabled by default, makes it possible (via the Web UI) to view the status of a connection and modify certain parameters of the brute force protection built into Nextcloud Server.

The user interface added by this app is found under *Administration settings -\> Security* under the *Brute-force IP whitelist* heading.

Currently an admin can view the status of the IP address they are connecting from as well as specify IPv4 or IPv6 addresses and ranges to exempt from brute force protection.

Additional enhancements may be made in the future, within this app and/or in combination with Nextcloud Server for additional monitoring or behavior adjustments related to brute force protection.

> **注意**
>
> Disabling the `bruteforcesettings` app does **not** disable brute force protection. The protection is built into Nextcloud Server core and is always active. Disabling the app only removes the ability to manage brute force settings from the Web interface.

> **警告**
>
> You would need to adjust the parameter `auth.bruteforce.protection.enabled` in your Nextcloud `config.php` to disable brute force protection, which is **heavily discouraged for production servers**, particularly if your server is reachable via a public IP address. It allows an attacker to iterate over all users and their passwords as well as two-factor verifications afterwards ultimately leading to admin access.

### `occ` commands

There are several brute force related `occ` commands under `occ security`.

### Brute force protection and load balancers/reverse proxies

If you are behind a reverse proxy or load balancer it is important you make sure it is setup properly. Especially the **trusted_proxies** and **forwarded_for_headers** config.php variables need to be set correctly. Otherwise it can happen that Nextcloud actually starts throttling all traffic coming from the reverse proxy or load balancer. For more information see [Reverse proxy](/link/934).

## Troubleshooting

### Overview

On most setups Nextcloud will work out of the box without any issues. If you run into a situation where logging in or connecting is often very slow for multiple users, the first step is to check your Nextcloud Server logs to see what IP addresses are being detected (you will need to adjust your `loglevel` to `1` temporarily to do so).

Look for entries that start with any of the following:

- Bruteforce attempt from \[...\]
- IP address throttled \[...\]
- IP address blocked \[...\]

If all clients appear to be coming from the same IP address and that IP address happens to be your proxy, you need to review your `trusted_proxies` configuration.

If the IP address is a common connection point, such as a multi-user office location, it can be an option to whitelist it, with the draw back that users have to be trust-worthy.

For testing purposes you want want to whitelist your own IP address to see if the problem disappears. If it does - and assuming your proxy configuration is correct - you may have a client/device in your network that is misbehaving and generating invalid login attempts from your IP address.

You can use the occ security:bruteforce:attempts command to check the realtime status for a given IP address.

> **提示**
>
> The bruteforce_attempts database table will be empty if you're using a distributed memory cache since the database backend is no longer used unless it is the only option available.

### Excluding IP addresses from brute force protection

> **提示**
>
> Most nuisance triggering of brute force protection can be resolved through proper configuration of reverse proxies. In other cases, select IP addresses that need to be whitelisted can be configured within this app (while leaving brute force protection enabled). This can be useful for testing purposes or when there are a lot of people (or devices) connecting from a known, single IP address.

It's possible to exclude IP addresses from the brute force protection.

- Make sure the `bruteforcesettings` app is enabled (it is by default)
- Login as admin and go to **Administration settings -\> Security**

> **警告**
>
> Any excluded IP address can perform authentication attempts without any throttling. It's best to exclude as few IP addresses as you can, or even none at all.

## Brute force protection vs fail2ban

Nextcloud's built-in brute force protection and fail2ban are complementary tools that operate at different layers of the stack. Using both together is recommended for production servers.

**Nextcloud brute force protection** is built into Nextcloud Server itself (the `bruteforcesettings` app provides the admin UI and exclusion settings, but the protection runs regardless). It works at the **application layer**: it detects suspicious login patterns and adds progressively longer delays to requests from the offending IP address. It has full context about Nextcloud-specific endpoints and credentials, and it activates automatically without any operating system configuration.

**fail2ban** works at the **OS/network layer**. It watches log files for failed login entries and instructs the system firewall (e.g. `iptables` or `nftables`) to block the offending IP outright. Blocked requests are dropped before they reach the web server, PHP, or the database, saving server resources entirely.

The two approaches are not mutually exclusive:

- Nextcloud brute force protection handles application-level throttling transparently, including for API clients and mobile apps, with no system configuration required.
- fail2ban reduces server load by blocking repeat offenders at the network level before their requests consume any application resources.

For setup instructions for fail2ban with Nextcloud, see [Setup fail2ban](/link/903).


# Memory caching

You can significantly improve your Nextcloud server performance with memory caching, where frequently-requested objects are stored in memory for faster retrieval. There are two types of caches to use: a PHP opcode cache, which is commonly called *opcache*, and data cache for your web server, commonly called "memcache".

> **提示**
>
> If you do not install and enable a local memcache you will see a warning on your Nextcloud admin page. **A memcache is not required. You may safely ignore the warning if you prefer.** If you enable only a distributed cache (`memcache.distributed`) in your `config.php` and not a local cache (`memcache.local`) you will still see the cache warning.

A **PHP opcache** stores compiled PHP scripts, so they don't need to be re-compiled every time they are called. PHP bundles the Zend OPcache in core since version 5.5, so you don't need to install an opcache manually.

**Data caching** is supplied by the user. Nextcloud supports multiple memory caching backends, so you can choose the type of memcache that best fits your needs. The supported caching backends are:

- [APCu](https://pecl.php.net/package/APCu) (APCu 4.0.6 and up required).

  A local cache for systems.

- [Redis](https://redis.io/open-source/) (4.0.0 and up required); [Valkey](https://valkey.io/) and [KeyDB](https://docs.keydb.dev/) are expected to work as Redis-compatible backends.

  > **提示**
  >
  > Automated/formal testing currently only occurs against Redis Open Source using the redis PHP extension and against Valkey using the Nextcloud keyvalue cache provider. KeyDB is expected to work as compatible backends as well, but are not formally tested.

  For local and distributed caching, as well as transactional file locking.

- [Memcached](https://www.memcached.org/)

  For distributed caching.

Data caches, or memcaches, must be explicitly configured in Nextcloud by installing and enabling your desired cache, and then adding the appropriate entry to `config.php` (See [Configuration Parameters](/link/919) for an overview of all possible config parameters).

## Recommendations based on type of deployment

You may use both a local and a distributed cache. Recommended caches are APCu and Redis or Valkey. After installing and enabling your chosen memcache (data cache), verify that it is active by running [PHP version and information](/link/1071).

> **提示**
>
> See specific cache configuration options under the appropriate section further down.

### Small/Private home server

Only use APCu:

    'memcache.local' => '\OC\Memcache\APCu',

### Organizations with single-server

Use Redis for everything except local memcache:

    'memcache.local' => '\OC\Memcache\APCu',
    'memcache.distributed' => '\OC\Memcache\Redis',
    'memcache.locking' => '\OC\Memcache\Redis',
    'redis' => [
         'host' => 'localhost',
         'port' => 6379,
    ],

### Organizations with clustered setups

Use APCu for local cache and either Redis cluster ...:

    'memcache.local' => '\OC\Memcache\APCu',
    'memcache.distributed' => '\OC\Memcache\Redis',
    'memcache.locking' => '\OC\Memcache\Redis',
    'redis.cluster' => [
        'seeds' => [ // provide some/all of the cluster servers to bootstrap discovery, port required
           'cache-cluster:7000',
           'cache-cluster:7001',
        ],
     ],

... or Memcached cluster ...:

    'memcache.local' => '\OC\Memcache\APCu',
    'memcache.distributed' => '\OC\Memcache\Memcached',
    'memcache.locking' => '\OC\Memcache\Memcached',
    'memcached_servers' => [
        [ 'server1.example.com', 11211 ],
        [ 'server2.example.com', 11211 ],
     ],

... for distributed and locking caches.

> **提示**
>
> If you run multiple web servers and enable a distributed cache in your `config.php` (`memcache.distributed`) or a file locking provider (`memcache.locking`) you need to make sure that they are referring to the very same memcache server/cluster and not to `localhost` or a unix socket.

### Additional notes for Redis vs. APCu on memory caching

APCu is faster for local caching than Redis. If you have enough memory, use APCu for Memory Caching and Redis for File Locking. If you are low on memory, use Redis for both.

## APCu

APCu is a data cache, and it is available in most Linux distributions. On Red Hat/CentOS/Fedora systems install `php-pecl-apcu`. On Debian/Ubuntu/Mint systems install `php-apcu`.

After restarting your Web server, add this line to your `config.php` file:

    'memcache.local' => '\OC\Memcache\APCu',

Refresh your Nextcloud admin page, and the cache warning should disappear.

Depending on your installation size and the number of users and interactions with the system you may want to adapt the `apc.shm_size` setting in your `php.ini`. The default value is 32M which is usually too low for Nextcloud. A good starting point is 128M. If you have a lot of users and/or a lot of apps installed you may want to increase this value further. Keep in mind that this memory needs to be available in your system's memory and kept in mind when sizing the amount of workers on your server.

A frequently resetting cache can lead to unexpected slow downs when the cache is being cleared and refilled.

There is an admin check trying to detect too low memory sizing, but make sure to monitor the APCu cache status to see if the cache is full and if you need to increase the size. [APCu provides a script](https://github.com/krakjoe/apcu/blob/master/apc.php) that can help with this, otherwise the [serverinfo app](https://github.com/nextcloud/serverinfo) in Nextcloud can also show the APCu cache status.

## Redis / Valkey using the Nextcloud `KeyValueCache`

> **提示**
>
> The KeyValueCache was added with Nextcloud 34.0.2.

The `KeyValueCache` cache is a brand-independent cache backend for key-value stores like [Valkey](https://valkey.io/) or [Redis](https://redis.io/open-source/). These are excellent modern memcaches to use for distributed caching, and as a key-value store for [Transactional File Locking](/link/969) because they guarantee that cached objects are available for as long as they are needed.

Unlike the `phpredis` backend described in the next section, the `KeyValueCache` does not require a PHP extension: it is built on the [predis](https://github.com/predis/predis) library which is bundled with Nextcloud. You only need to install and run a Valkey or Redis compatible server and configure it in `config.php`.

> **提示**
>
> When the cache server is not located on the same machine the performance may be impacted due to network overhead compared to the `php-redis` based backend. In those cases it may be preferable to use the `php-redis` backend instead.

On Debian/Ubuntu/Mint, install `valkey-server` or `redis-server`. On CentOS and Fedora, install `valkey` or `redis`. Depending on your distribution the server might not start automatically, so you may need to use your service manager to start the server, and to launch it at boot as a daemon.

You can verify that the daemon is running with `ps ax`:

    ps ax | grep valkey
    22203 ? Ssl    0:00 /usr/bin/valkey-server 127.0.0.1:6379

Add the appropriate entries to your `config.php`, and refresh your Nextcloud admin page.

### KeyValueCache configuration in Nextcloud (config.php)

For best performance, use the `KeyValueCache` for file locking by adding this:

    'memcache.locking' => '\OC\Memcache\KeyValueCache',

Additionally, you should use it for the distributed server cache:

    'memcache.distributed' => '\OC\Memcache\KeyValueCache',

Furthermore, you could use it for the local cache like so, but it's not recommended (see warning below):

    'memcache.local' => '\OC\Memcache\KeyValueCache',

> **注意**
>
> Using a key-value store server for local cache on a multi-server setup can cause issues. Also, even on a single-server setup, APCu (see section above) should be faster.

When using the `keyvalue` cache for any of the above cache settings, you also need to specify the `memcache.kvstore` configuration in `config.php`. Three topologies are supported: a single server (`server`), a Sentinel managed replication set (`sentinel`), and a server cluster (`seeds`). Configure exactly one of them.

The following options are available when using a single server (all but `server` are optional):

    'memcache.locking' => '\OC\Memcache\KeyValueCache',
    'memcache.distributed' => '\OC\Memcache\KeyValueCache',
    'memcache_customprefix' => 'mynextcloudprefix',
    'memcache.kvstore' => [
       'server' => [
          'host' => 'cache-host.example.com',
          'port' => 6379,
          // Protocol used to connect. One of 'tcp', 'tls' or 'unix'.
          // When omitted it is derived from the host (a leading '/' means 'unix').
          'protocol' => 'tcp',
       ],
       'user'         => 'nextcloud', // only sent when the server uses ACLs
       'password'     => 'password',
       'dbindex'      => 0,
       'timeout'      => 1.5,
       'read_timeout' => 1.5,
       'persistent'   => false, // keep the connection open across requests
    ],

The same optional parameters are available for the Sentinel and cluster topologies below and are applied to every node.

For a Sentinel managed replication setup, provide the name of the monitored service and one seed entry per Sentinel node (each seed uses the same format as the `server` entry above):

    'memcache.kvstore' => [
       'sentinel' => [
          'service' => 'mymaster',
          'seeds' => [
             ['host' => 'sentinel1.example.com', 'port' => 26379],
             ['host' => 'sentinel2.example.com', 'port' => 26379],
             ['host' => 'sentinel3.example.com', 'port' => 26379],
          ],
       ],
    ],

For a cluster, provide some or all of the cluster nodes to bootstrap discovery:

    'memcache.kvstore' => [
       'seeds' => [
          ['host' => 'cache-cluster.example.com', 'port' => 7000],
          ['host' => 'cache-cluster.example.com', 'port' => 7001],
       ],
    ],

> **提示**
>
> Selecting a numbered database with `dbindex` is only supported for single servers and Sentinel setups; clusters always use database 0, the support for numbered databases added with Valkey v9 is pending [upstream](https://github.com/predis/predis/issues/1696).

### Connecting over TLS

To connect via TCP over TLS, set the `protocol` of the server (or of each seed) to `tls` and provide the SSL context ([SSL context options](https://www.php.net/manual/en/context.ssl.php)):

    'memcache.kvstore' => [
       'server' => [
          'host' => 'cache-host.example.com',
          'port' => 6379,
          'protocol' => 'tls',
       ],
       'ssl_context' => [
          'local_cert' => '/certs/cache.crt',
          'local_pk' => '/certs/cache.key',
          'cafile' => '/certs/ca.crt',
       ],
    ],

### Connecting over UNIX socket

If you want to connect to a server configured to listen on a Unix socket (which is recommended if the server is running on the same system as Nextcloud), pass the socket path as the host. A leading slash in the host is automatically detected as a Unix socket, so no `protocol` or `port` is needed:

    'memcache.kvstore' => [
       'server' => [
          'host' => '/run/valkey/valkey.sock',
       ],
    ],

Update the server configuration (for example `/etc/valkey/valkey.conf`) accordingly: uncomment the Unix socket options and ensure the socket path matches your Nextcloud configuration.

Be sure to set the right permissions on the socket so that your web server can read and write to it. For this you typically have to add the web server user to the `valkey` (or `redis`) group:

    usermod -a -G valkey www-data

And modify the `unixsocketperm` setting of the server configuration accordingly:

    unixsocketperm 770

You might need to restart your web server and the cache server for the changes to take effect.

## Redis using the phpredis PHP extension

Redis is an excellent modern memcache to use for distributed caching, and as a key-value store for [Transactional File Locking](/link/969) because it guarantees that cached objects are available for as long as they are needed.

Nextcloud uses the PhpRedis PHP extension. This extension provides an API for communicating with Redis-compatible key-value stores. Redis Open Source is the formally tested backend; Valkey and KeyDB are expected to work as compatible backends as well.

The Redis PHP module must be version 2.2.6+. If you are running a Linux distribution that does not package the supported versions of this module, or does not package Redis at all, see [Memcached](/link/926).

On Debian/Ubuntu/Mint, install `redis-server` (or equivalent) and `php-redis`. Package names vary by distribution and backend.

On CentOS and Fedora, install `redis` (or equivalent) and `php-pecl-redis`. It will not start automatically, so you must use your service manager to start the `redis` server, and to launch it at boot as a daemon.

You can verify that the Redis daemon is running with `ps ax`:

    ps ax | grep redis
    22203 ? Ssl    0:00 /usr/bin/redis-server 127.0.0.1:6379

Restart your Web server, add the appropriate entries to your `config.php`, and refresh your Nextcloud admin page.

### Redis configuration in Nextcloud (config.php)

For best performance, use Redis for file locking by adding this:

    'memcache.locking' => '\OC\Memcache\Redis',

Additionally, you should use Redis for the distributed server cache:

    'memcache.distributed' => '\OC\Memcache\Redis',

Furthermore, you could use Redis for the local cache like so, but it's not recommended (see warning below):

    'memcache.local' => '\OC\Memcache\Redis',

> **注意**
>
> Using Redis for local cache on a multi-server setup can cause issues. Also, even on a single-server setup, APCu (see section above) should be faster.

When using Redis for any of the above cache settings, you also need to specify either the `redis` or `redis.cluster` configuration in `config.php`.

The following options are available to configure when using a single redis server (all but `host` and `port` are optional. For the latter two, see the next sections):

    'memcache.locking' => '\OC\Memcache\Redis',
    'memcache.distributed' => '\OC\Memcache\Redis',
    'memcache.local' =>'\OC\Memcache\Redis' ,
    'memcache_customprefix' => 'mynextcloudprefix',
    'redis' => [
       // 'host'      => see connection parameters below
       // 'port'      => see connection parameters below
      'user'          => 'nextcloud',
      'password'      => 'password',
      'dbindex'       => 0,
      'timeout'       => 1.5,
      'read_timeout'  => 1.5,
    ],

The following options are available to configure when using a redis cluster (all but `seeds` are optional):

    'memcache.locking' => '\OC\Memcache\Redis',
    'memcache.distributed' => '\OC\Memcache\Redis',
    'memcache.local' =>'\OC\Memcache\Redis' ,
    'memcache_customprefix' => 'mynextcloudprefix',
    'redis.cluster' => [
       'seeds' => [ // provide some/all of the cluster servers to bootstrap discovery, port required
          'cache-cluster:7000',
          'cache-cluster:7001',
          'cache-cluster:7002',
          'cache-cluster:7003',
          'cache-cluster:7004',
          'cache-cluster:7005'
       ],
       'failover_mode'   => \RedisCluster::FAILOVER_ERROR,
       'timeout'         => 0.0,
       'read_timeout'    => 0.0,
       'user'            => 'nextcloud',
       'password'        => 'password',
       'dbindex'         => 0,
    ],

> **提示**
>
> The port is required as part of the server URL. However, it is not necessary to list all servers: for example, if all servers are load balanced via the same DNS name, only that server name is required.

### Connecting to single Redis server over TCP

To connect to a remote or local Redis server over TCP use:

    'redis' => [
       'host' => 'redis-host.example.com',
       'port' => 6379,
    ],

### Connecting to single Redis server over TLS

To connect via TCP over TLS, add the following configuration:

    'redis' => [
       'host' => 'tls://127.0.0.1',
       'port' => 6379,
       'ssl_context' => [
          'local_cert' => '/certs/redis.crt',
          'local_pk' => '/certs/redis.key',
          'cafile' => '/certs/ca.crt',
          'verify_peer_name' => false,
       ],
    ],

### Connecting to Redis cluster over TLS

To connect via TCP over TLS, add the following configuration:

    'redis.cluster' => [
       'seeds' => [ // provide some/all of the cluster servers to bootstrap discovery, port required
          'cache-cluster:7000',
          'cache-cluster:7001',
       ],
       'ssl_context' => [
          'local_cert' => '/certs/redis.crt',
          'local_pk' => '/certs/redis.key',
          'cafile' => '/certs/ca.crt',
          'verify_peer_name' => false,
       ],
    ],

### Connecting to single Redis server over UNIX socket

If you want to connect to Redis configured 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:

    'redis' => [
       'host'     => '/run/redis/redis-server.sock',
       'port'     => 0,
    ],

Only "host" and "port" variables are required, the other ones are optional.

Update the redis configuration in `/etc/redis/redis.conf` accordingly: uncomment Unix socket options and ensure the "socket" and "port" settings match your Nextcloud configuration.

Be sure to set the right permissions on redis.sock so that your webserver can read and write to it. For this you typically have to add the webserver user to the redis group:

    usermod -a -G redis www-data

And modify the `unixsocketperm` of the `redis.conf` accordingly:

    unixsocketperm 770

You might need to restart apache and redis for the changes to take effect:

    systemctl restart apache2
    systemctl restart redis-server

Redis is very configurable; consult [the Redis documentation](http://redis.io/documentation) to learn more.

### Using the Redis session handler

If you are using Redis for locking and/or caching, you may also wish to use Redis for session management. Redis can be used for centralized session management across multiple Nextcloud application servers, unlike the standard files handler. If you use the Redis handler, though, you *MUST* ensure that session locking is enabled. As of this writing, the Redis session handler does *NOT* enable session locking by default, which can lead to session corruption in some Nextcloud apps that make heavy use of session writes such as Talk. In addition, even when session locking is enabled, if the application fails to acquire a lock, the Redis session handler does not currently return an error. Adding the following settings in your `php.ini` file will prevent session corruption when using Redis as your session handler: :

    redis.session.locking_enabled=1
    redis.session.lock_retries=-1
    redis.session.lock_wait_time=10000

More information on configuration of phpredis session handler can be found on the [PhpRedis GitHub page](https://github.com/phpredis/phpredis)

## Memcached

Memcached is a reliable oldtimer for shared caching on distributed servers, and performs well with Nextcloud with one exception: it is not suitable to use with [Transactional File Locking](/link/969) because it does not store locks, and data can disappear from the cache at any time (Redis is the best memcache for this).

> **提示**
>
> Be sure to install the **memcached** PHP module, and not memcache, as in the following examples. Nextcloud supports only the **memcached** PHP module.

Setting up Memcached is easy. On Debian/Ubuntu/Mint install `memcached` and `php-memcached`. The installer will automatically start `memcached` and configure it to launch at startup.

On Red Hat/CentOS/Fedora install `memcached` and `php-pecl-memcached`. It will not start automatically, so you must use your service manager to start `memcached`, and to launch it at boot as a daemon.

You can verify that the Memcached daemon is running with `ps ax`:

    ps ax | grep memcached
    19563 ? Sl 0:02 /usr/bin/memcached -m 64 -p 11211 -u memcache -l
    127.0.0.1

Restart your Web server, add the appropriate entries to your `config.php`, and refresh your Nextcloud admin page.

### Memcached configuration in Nextcloud (config.php)

This example uses APCu for the local cache, Memcached as the distributed memcache, and lists all the servers in the shared cache pool with their port numbers:

    'memcache.local' => '\OC\Memcache\APCu',
    'memcache.distributed' => '\OC\Memcache\Memcached',
    'memcache.locking' => '\OC\Memcache\Memcached',
    'memcached_servers' => [
         [ 'server0.example.com', 11211 ],
         [ 'server1.example.com', 11211 ],
         [ 'server2.example.com', 11211 ],
     ],

## Cache Directory location

The cache directory defaults to `data/$user/cache` where `$user` is the current user. You may use the `'cache_path'` directive in `config.php` (See [Configuration Parameters](/link/919)) to select a different location.

## Cache Key Prefix for Redis or Memcached

By default, Nextcloud generates a semi-unique prefix for cache keys using information like instance ID, version etc. to mitigate the problem of collisions when using the same cache for multiple Nextcloud instances. If you want to make sure to prevent collisions altogether, you can use the following setting to define your custom prefix:

    'memcache_customprefix' => 'mynextcloudprefix',

This also allows you to create ACLs in Redis and limit the keys specific users can access (e.g. if you want to isolate specific Nextcloud instances when using the same cache). This may be security-relevant for you.


# Dashboard app

The Nextcloud Dashboard is your starting point of the day, giving users an overview of your upcoming appointments, urgent emails, chat messages, incoming tickets, latest tweets and much more! Users can add the widgets they like and change the background to their liking.

## Enabling the dashboard app

The Dashboard App is shipped and enabled by default. If it is not enabled simply go to your Nextcloud Apps page to enable it.

## Configuring your Nextcloud for the dashboard app

The dashboard widgets are provided by apps and have a unique identifier. This can be used to customize the default layout of the dashboard as an administrator. The layout is stored as a comma-separated list of widget identifiers.

The layout of an existing user can be read with the following command:

    occ user:setting admin dashboard layout

The layout of the dashboard for a specific user can be set with the following command:

    occ user:setting admin dashboard layout "calendar,files,activity"

The default layout of the dashboard for all users can be set with the following command:

    occ config:app:set dashboard layout --value="files,activity,calendar"

Changing the default layout will not affect existing users that already have a custom layout stored.

It is possible to replace the default app, which is the dashboard app, with a custom app with the following command:

> occ config:app:set core defaultpage --value "/apps/files/extstoragemounts"

# Domain Change

Changing the domain after the first setup is currently not supported by Nextcloud. That is mainly because Nextcloud's apps don't support changing the domain after they are set up.

> **提示**
>
> This documentation will get updated with steps what needs to be done if you want to change the domain as soon as this feature is available.

# Email

Nextcloud is capable of sending password reset emails, notifying users of new file shares, changes in files, and activity notifications. Your users configure which notifications they want to receive on their Personal pages.

Nextcloud does not contain a full email server, but rather connects to your existing mail server. You must have a functioning mail server for Nextcloud to be able to send emails. You may have a mail server on the same machine as Nextcloud, or it may be a remote server.

To access the setup page below log in with an admin account. Click on your avatar and then click **Settings**. On the left side under Administration and click Basic settings.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/smtp-config-wizard.png)

With the wizard, connecting Nextcloud to your mail server is fast and easy. The wizard fills in the values in `config/config.php`, so you may use either or both as you prefer.

The Nextcloud Email wizard supports three types of mail server connections: SMTP, qmail, and Sendmail. Use the SMTP configurator for a remote server or Sendmail when your mail server is on the same machine as Nextcloud.

> **提示**
>
> The Sendmail option refers to the Sendmail SMTP server and any drop-in Sendmail replacement such as Postfix, Exim, or Courier. All of these include a `sendmail` binary, and are freely-interchangeable.

## Mail Providers

> *New in version 30*

A mail provider is an app that provides outbound mail service to Nextcloud and allows the sending of system emails directly through a user's configured personal email account instead of the system email account. At present, this functionality is limited to calendar invitations. This feature automatically matches a users email address to a configured mail provider account, when a system message is sent. The only app that supports this functionality at present is Nextcloud Mail 4.1 or higher, a configured email account is required.

## Configuring an SMTP server

You need the following information from your mail server administrator to connect Nextcloud to a remote SMTP server:

> **注意**
>
> There were changes to the 3rd party mailer library in Nextcloud 26:
>
> - STARTTLS cannot be enforced; it is used automatically if the mail server supports it. Set the encryption type to **None/STARTTLS** to allow this automatic upgrade. See [here](/link/929) for an example on how to configure self-signed certificates.
> - NTLM authentication for Microsoft Exchange is not supported by the new mailer library. Try using [basic authentication](https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/authentication-and-ews-in-exchange#basic-authentication) instead.
> - Outlook and Microsoft Exchange have discontinued support for Basic authentication. It is no longer possible to use their services as your default email handler.

- Encryption type: None/STARTTLS or SSL

- The From address you want your outgoing Nextcloud mails to use

- Whether authentication is required

- Authentication: when authentication is required, the underlying mailer will try the following authentication methods in the order they're listed:

  > - CramMd5
  > - Login
  > - Plain
  > - XOAuth2

- The server's IP address or fully-qualified domain name and the SMTP port

- Login credentials (if required)

> **提示**
>
> The `overwrite.cli.url` parameter from `config.php` will be used for the SMTP EHLO.

Your changes are saved immediately, and you can click the Send Email button to test your configuration. This sends a test message to the email address you configured on your Personal page. The test message says:

    If you received this email, the settings seem to be correct.

    --
    Nextcloud
    a safe home for all your data

## Configuring Sendmail/qmail

Configuring Sendmail or qmail requires only that you select one of them instead of SMTP, and then enter your desired return email address.

In most cases the `SMTP` option is best, since you will be able to control all of your mail server options in one place, in your mail server configuration then.

## Using email templates

We designed a mechanism that generates emails which follow the theming settings and look the same in all the different email clients out there.

> **提示**
>
> If, for some reason, you need text-only emails, consider simply configuring this on the client side or let the receiving (or even sending) mail server drop the HTML part. Note that there is no security impact from **sending** HTML emails, just from displaying them and thus any security risk can only be mitigated by disabling showing HTML on the client (or removing the HTML part in the mail server).

### Modifying the look of emails beyond the theming app capabilities

You can overwrite templates by writing a class that implements the template interface (or extends it to not need to copy over everything). Easiest way is to then put this class into an app and load it so you do not need to patch it on every update.

This is the interface of the class that needs to be implemented: <https://github.com/nextcloud/server/blob/master/lib/public/Mail/IEMailTemplate.php>

That is the implementation that could be extended and used to see how it works: <https://github.com/nextcloud/server/blob/master/lib/private/Mail/EMailTemplate.php>

An example from [a Nextcloud portal article](https://portal.nextcloud.com/article/customized-email-templates-29.html):

1.  Look at the source code of extended class [OC\Mail\EMailTemplate::class](https://github.com/nextcloud/server/blob/master/lib/private/Mail/EMailTemplate.php)
2.  Then override what you need in your own OCMailEMailTemplate::class extension

**Example:**

Let's assume that we need to override the email header:

    <?php

    namespace \OCA\MyApp;

    use OC\Mail\EMailTemplate;

    class MyClass extends EMailTemplate
    {
       protected string $header = <<<EOF
          <table align="center" class="wrapper">
                // your theme email header modification
          </table>
       EOF;
    }

3.  Then in `config/config.php` change `mail_template_class` to your class namespace:

        'mail_template_class' => 'OCA\\MyApp\\MyClass',

You will find a detailed step by step guide in our [support portal](https://portal.nextcloud.com/article/customized-email-templates-29.html).

## Setting mail server parameters in config.php

If you prefer, you may set your mail server parameters in `config/config.php`. The following examples are for SMTP, Sendmail, and Qmail.

### SMTP

If you want to send email using a local or remote SMTP server it is necessary to enter the name or IP address of the server, optionally followed by a colon separated port number, e.g. **:425**. If this value is not given the default port 25/tcp will be used unless you change that by modifying the **mail_smtpport** parameter.

    "mail_smtpmode"     => "smtp",
    "mail_smtphost"     => "smtp.server.dom:425",

or

    "mail_smtpmode"     => "smtp",
    "mail_smtphost"     => "smtp.server.dom",
    "mail_smtpport"     => 425,

If a malware or SPAM scanner is running on the SMTP server it might be necessary that you increase the SMTP timeout to e.g. 30s:

    "mail_smtptimeout"  => 30,

If the SMTP server accepts insecure connections, the default setting can be used:

    "mail_smtpsecure"   => '',

The connection will be upgraded automatically via STARTTLS if the SMTP server supports it.

If required by the SMTP server, a secure SSL/TLS connection can be enforced via the SMTPS protocol which uses the port 465/tcp:

    "mail_smtphost"     => "smtp.server.dom:465",
    "mail_smtpsecure"   => 'ssl',

And finally it is necessary to configure if the SMTP server requires authentication, if not, the default values can be taken as is.

    "mail_smtpauth"     => false,
    "mail_smtpname"     => "",
    "mail_smtppassword" => "",

If SMTP authentication is required you have to set the required username and password.

    "mail_smtpauth"     => true,
    "mail_smtpname"     => "username",
    "mail_smtppassword" => "password",

### Sendmail

If you want to use the well known Sendmail program to send email, it is necessary to have an installed and working email system on your \*nix server. The sendmail binary (**/usr/sbin/sendmail**) is usually part of that system. Nextcloud should be able to send email out of the box.

    "mail_smtpmode"     => "sendmail",
    "mail_smtphost"     => "127.0.0.1",
    "mail_smtpport"     => 25,
    "mail_smtptimeout"  => 10,
    "mail_smtpsecure"   => "",
    "mail_smtpauth"     => false,
    "mail_smtpauthtype" => "LOGIN",
    "mail_smtpname"     => "",
    "mail_smtppassword" => "",

### qmail

If you want to use the qmail program to send email, it is necessary to have an installed and working qmail email system on your server. The qmail binary installed on your server will then be used to send email. Nextcloud should be able to send email out of the box.

    "mail_smtpmode"     => "qmail",
    "mail_smtphost"     => "127.0.0.1",
    "mail_smtpport"     => 25,
    "mail_smtptimeout"  => 10,
    "mail_smtpsecure"   => "",
    "mail_smtpauth"     => false,
    "mail_smtpauthtype" => "LOGIN",
    "mail_smtpname"     => "",
    "mail_smtppassword" => "",

## Send a test email

To test your email configuration, save your email address in your personal settings and then use the **Send email** button in the *Email Server* section of the Admin settings page.

## Troubleshooting

### Enabling debug mode

If you are unable to send email, it might be useful to activate further debug messages by enabling the `mail_smtpdebug` parameter and temporarily setting your NC loglevel to DEBUG:

    "mail_smtpdebug" => true,
    "loglevel" => 0,

Be cautious setting your `loglevel` to DEBUG (`0`) since it'll apply to everything occurring on your NC instance, not just email. And don't forget to set it back to a more reasonable level when you're done troubleshooting:

    "mail_smtpdebug" => false,
    "loglevel" => 2,

> **提示**
>
> Immediately after pressing the **Send email** button, as described before, several **SMTP -\> get_lines(): ...** messages appear on the screen. This is expected behavior and can be ignored.

### Why is my web domain different from my mail domain?

The default domain name used for the sender address is the hostname where your Nextcloud installation is served. If you have a different mail domain name you can override this behavior by setting the following configuration parameter:

    "mail_domain" => "example.com",

This setting results in every email sent by Nextcloud (for example, the password reset email) having the domain part of the sender address appear as follows:

    no-reply@example.com

### How can I find out if an SMTP server is reachable?

Use the ping command to check the server availability:

    ping smtp.server.dom

    PING smtp.server.dom (ip-address) 56(84) bytes of data.
    64 bytes from your-server.local.lan (192.168.1.10): icmp_req=1 ttl=64
    time=3.64ms

### How can I find out if the SMTP server is listening on a specific TCP port?

The best way to get mail server information is to ask your mail server admin. If you are the mail server admin, or need information in a hurry, you can use the `netstat` command. This example shows all active servers on your system, and the ports they are listening on. The SMTP server is listening on localhost port 25.

    # netstat -pant

    Active Internet connections (servers and established)
    Proto Recv-Q Send-Q Local Address   Foreign Address  State  ID/Program name
    tcp    0      0    0.0.0.0:631     0.0.0.0:*        LISTEN   4418/cupsd
    tcp    0      0    127.0.0.1:25    0.0.0.0:*        LISTEN   2245/exim4
    tcp    0      0    127.0.0.1:3306  0.0.0.0:*        LISTEN   1524/mysqld

- 25/tcp is unencrypted smtp
- 110/tcp/udp is unencrypted pop3
- 143/tcp/udp is unencrypted imap4
- 465/tcp is encrypted submissions
- 587/tcp is opportunistically-encrypted submission
- 993/tcp/udp is encrypted imaps
- 995/tcp/udp is encrypted pop3s

### How can I determine if the SMTP server supports the SMTPS protocol?

A good indication that the SMTP server supports the SMTPS protocol is that it is listening on the submissions port **465**.

### How can I determine what authorization and encryption protocols the mail server supports?

SMTP servers usually announce the availability of STARTTLS immediately after a connection has been established. You can easily check this using the `telnet` command.

> **提示**
>
> You must enter the marked lines to obtain the information displayed.

    telnet smtp.domain.dom 25

    Trying 192.168.1.10...
    Connected to smtp.domain.dom.
    Escape character is '^]'.
    220 smtp.domain.dom ESMTP Exim 4.80.1 Tue, 22 Jan 2013 22:39:55 +0100
    EHLO your-server.local.lan                   # <<< enter this command
    250-smtp.domain.dom Hello your-server.local.lan [ip-address]
    250-SIZE 52428800
    250-8BITMIME
    250-PIPELINING
    250-AUTH PLAIN LOGIN CRAM-MD5                 # <<< Supported auth protocols
    250-STARTTLS                                  # <<< Encryption is supported
    250 HELP
    QUIT                                          # <<< enter this command
    221 smtp.domain.dom closing connection
    Connection closed by foreign host.

### How can I send mail using self-signed certificates or use STARTTLS with self signed certificates?

To disable peer verification or to use self signed certificates, add the following to your `config/config.php`:

    "mail_smtpstreamoptions" => array(
        'ssl' => array(
            'allow_self_signed' => true,
            'verify_peer' => false,
            'verify_peer_name' => false
        )
    ),

### All emails keep getting rejected even though only one email address is invalid.

Partial sending, i. e. sending to all but the faulty email address is not possible.

> **提示**
>
> Immediately after pressing the **Send email** button, as described before, several **SMTP -\> get_lines(): ...** messages appear on the screen. This is expected behavior and can be ignored.


# Linking external sites

You can embed external websites or documents inside your Nextcloud pages with the **External sites** app, as this screenshot shows.

![*Click to enlarge*](https://docs.cocobook.com/uploads/images/gallery/2026-10/external-sites-1.png)

Click to enlarge

This is useful for quick access to important pages such as the Nextcloud manuals and informational pages for your company, and for presenting external pages inside your custom Nextcloud branding, if you use your own custom themes.

The External sites app can be easily installed from the app store. Go to **Settings \> Apps \> Customization** to enable it. Then go to your Nextcloud **Settings \> Administration \> External sites** to create your links, which are saved automatically.

Each link can have a unique icon, which can be uploaded in the admin settings. If you select a language, the link will only be displayed for users with the selected language. This allows you to have different documentation links for users depending on their language.

It is also possible to add links for a special device (recognized by the user agent). Currently the following options are available: All devices, Android app, iOS app, Desktop client and all others (Browsers).

It is also possible to add links only for members of a given group.

![*Click to enlarge*](https://docs.cocobook.com/uploads/images/gallery/2026-10/external-sites-2.png)

Click to enlarge

The links appear in the Nextcloud menu on the top or in the settings menu, after reloading the page.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/external-sites-3.png)

## Configurations preventing embedding

Your links may or may not work correctly due to the various ways that Web browsers and Web sites handle HTTP and HTTPS URLs, and because the External Sites app embeds external links in IFrames. Modern Web browsers try very hard to protect Web surfers from dangerous links, and safety apps like [Privacy Badger](https://www.eff.org/privacybadger) and ad-blockers may block embedded pages. It is strongly recommended to enforce HTTPS on your Nextcloud server; do not weaken this, or any of your security tools, just to make embedded Web pages work. After all, you can freely access them outside of Nextcloud.

Most Web sites that offer login functionalities use the `X-Frame-Options` or `Content-Security-Policy` HTTP header which instructs browsers to not allow their pages to be embedded for security reasons (e.g. "Clickjacking"). You can usually verify the reason why embedding the website is not possible by using your browser's console tool. For example, this page has an invalid SSL certificate.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/external-sites-4.png)

On this page, X-Frame-Options prevents the embedding.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/external-sites-5.png)

There is also a redirect option, which allows that those websites can still be added for quick access. Instead of embedding the website the user will be redirected to it.


# Language & Locale

## Default language

In normal cases Nextcloud will automatically detect the language of the Web-GUI. If this does not work properly or you want to make sure that Nextcloud always starts with a given language, you can set a **default_language** parameter in the `config/config.php`.

> **提示**
>
> The `default_language` parameter only applies when the browser sends no language preference and the user has not set their own. Accepts ISO 639-1 codes such as `en` (English), `fr` (French), `de` (informal German), or `de_DE` (formal German).

    "default_language" => "en",

## Force language

If you want to force a specific language, users will no longer be able to change their language in the personal settings. You can set a **force_language** parameter in the `config/config.php`.

    "force_language" => "en",

If users shall be unable to change their language, but users have different languages, this value can be set to `true` instead of a language code.

> **提示**
>
> Please check [Transifex language codes](https://explore.transifex.com/languages/) for the list of valid language codes.

## Default locale

The locale is used to define how dates and other formats are displayed. Nextcloud should automatically pick an appropriate locale based on your current language. Users can modify their locale inside their settings panel. If that does not work properly or if you want to make sure that Nextcloud always starts with a given locale, you can set a **default_locale** parameter in the `config/config.php`.

> **提示**
>
> The default_locale parameter is only used when the user hasn't configured own locale preferences.

    "default_locale" => "en_US",

## Force locale

If you want to force a specific locale, users will no longer be able to change their locale in the personal settings. You can set a **force_locale** parameter in the `config/config.php`.

    "force_locale" => "en_US",

> **提示**
>
> Please check [the list of MomentJS supported locales](https://github.com/moment/moment/tree/2.18.1/locale) for the list of valid locales.

# Logging

Use your Nextcloud log to review system status, or to help debug problems. You may adjust logging levels, and choose how and where log data is stored. If additional event logging is required, you can optionally activate the **admin_audit** app.

When `file` based logging is utilized, both the Nextcloud log and, optionally, the **admin_audit** app log can be viewed within the Nextcloud interface under *Administration settings -\> Logging* (this functionality is provided by the **logreader** app).

Further configuration and usage details for both the standard Nextcloud log and the optional **admin_audit** app log can be found below.

## Log level

Logging levels range from **DEBUG**, which logs all activity, to **FATAL**, which logs only fatal errors.

- **0**: DEBUG: All activity; the most detailed logging.
- **1**: INFO: Activity such as user logins and file activities, plus warnings, errors, and fatal errors.
- **2**: WARN: Operations succeed, but with warnings of potential problems, plus errors and fatal errors.
- **3**: ERROR: An operation fails, but other services and operations continue, plus fatal errors.
- **4**: FATAL: The server stops.

By default the log level is set to **2** (WARN). Use **DEBUG** when you have a problem to diagnose, and then reset your log level to a less-verbose level as **DEBUG** outputs a lot of information, and can affect your server performance.

Logging level parameters are set in the `config/config.php` file.

## Log type

### errorlog

All log information will be sent to PHP `error_log()`.

    "log_type" => "errorlog",

Log entries will be prefixed with `[nextcloud]`.

### file

All log information will be written to a separate log file which can be viewed using the log viewer on your Admin page. By default, a log file named **nextcloud.log** will be created in the directory which has been configured by the **datadirectory** parameter in `config/config.php`.

The desired date format can optionally be defined using the **logdateformat** parameter in `config/config.php`. By default the [PHP date function](http://www.php.net/manual/en/function.date.php) parameter `c` is used, and therefore the date/time is written in the format `2013-01-10T15:20:25+02:00`. By using the date format in the example below, the date/time format will be written in the format `January 10, 2013 15:20:25`.

    "log_type" => "file",
    "logfile" => "nextcloud.log",
    "loglevel" => 3,
    "logdateformat" => "F d, Y H:i:s",

#### Additional file-based logging parameters

The following optional parameters can also be set in `config/config.php`:

**logfilemode**  
Sets the file permissions (in octal notation) for the log file.

Defaults to `0640`.

    "logfilemode" => 0640,

**logtimezone**  
Sets the timezone used for log timestamps. See the [PHP list of supported timezones](https://www.php.net/manual/en/timezones.php).

Defaults to `UTC`.

    "logtimezone" => "Europe/Berlin",

**log_rotate_size**  
Enables log rotation and limits the total size of log files. The value is specified in bytes. When the current log file reaches this size a new log file is created. If a rotated log file already exists it will be overwritten. Set to `0` to disable rotation.

Defaults to `104857600` (100 MB).

    "log_rotate_size" => 100 * 1024 * 1024,

**log.backtrace**  
When enabled, a backtrace is appended to every log line, not only to exceptions. This significantly increases log size and should only be used for debugging.

Defaults to `false`.

    "log.backtrace" => true,

**log_query**  
Appends all database queries and their parameters to the log file. Use this only for debugging as it produces very large log files.

Defaults to `false`.

    "log_query" => true,

**loglevel_frontend**  
Sets a separate log level for messages originating from the Nextcloud frontend (browser). Accepts the same values as `loglevel` (0–4).

Defaults to `2` (WARN).

    "loglevel_frontend" => 2,

**loglevel_dirty_database_queries**  
Sets the log level at which dirty database queries (queries executed after the response has already been sent) are logged.

Defaults to `0` (DEBUG).

    "loglevel_dirty_database_queries" => 0,

### syslog

All log information will be sent to your default syslog daemon.

    "log_type" => "syslog",
    "syslog_tag" => "Nextcloud",
    "logfile" => "",
    "loglevel" => 3,

### systemd

All log information will be sent to Systemd journal. Requires [php-systemd](https://github.com/systemd/php-systemd) extension.

    "log_type" => "systemd",
    "syslog_tag" => "Nextcloud",

## Conditional logging (log.condition)

Nextcloud supports conditional overrides that temporarily increase the log level to **DEBUG** when certain criteria are met. This is useful for diagnosing problems in production without flooding the entire log with debug output.

The `log.condition` parameter is set in `config/config.php`.

### Basic conditions

At the top level you can specify one or more of the following keys. When *any* of them match, the log level for that request is set to **DEBUG**:

**shared_secret**  
Match requests that pass the query parameter `log_secret` with this value.

**users**  
An array of user IDs. If the currently authenticated user is in the list, the condition is satisfied.

**apps**  
An array of app identifiers. Any log message whose app context matches one of these apps will be logged at DEBUG level.

Example – enable debug logging for user `jane` and the `files` app:

    'log.condition' => [
        'users' => ['jane'],
        'apps' => ['files'],
    ],

### Advanced compound conditions (matches)

The `matches` key accepts an array of condition groups. Each group can combine all of the keys above plus:

**message**  
A substring that must appear in the log message.

**loglevel**  
The log level to apply when this group matches (instead of the default DEBUG / `0`).

All keys within a single group must match for the group to apply (logical AND). Multiple groups are evaluated independently (logical OR).

Example – log all messages from the `files` app at INFO level, and log any message containing `"Lock"` for user `admin` at DEBUG level:

    'log.condition' => [
        'matches' => [
            [
                'apps' => ['files'],
                'loglevel' => 1,
            ],
            [
                'users' => ['admin'],
                'message' => 'Lock',
                'loglevel' => 0,
            ],
        ],
    ],

### Using a shared secret for on-demand debugging

You can trigger debug logging for a single request by adding a `log_secret` query parameter. Set a secret in `config/config.php`:

    'log.condition' => [
        'shared_secret' => '57b58edb6637fe3059b3595cf9c41b9',
    ],

Then call your Nextcloud URL with the secret appended:

    https://cloud.example.com/index.php?log_secret=57b58edb6637fe3059b3595cf9c41b9

> **注意**
>
> Keep the shared secret private. Anyone who knows it can enable debug-level logging on your instance.

## Log fields explained

### Example log entries

    {
        "reqId":"TBsuA2uE86DiOD0S8f9j",
        "level":1,
        "time":"April 13, 2021 16:55:37",
        "remoteAddr":"192.168.56.1",
        "user":"admin",
        "app":"admin_audit",
        "method":"GET",
        "url":"/ocs/v1.php/cloud/users?disabled",
        "message":"Login successful: \"admin\"",
        "userAgent":"curl/7.68.0",
        "version":"21.0.1.1"
    }

    {
        "reqId":"ByeDVLuwkXKMfLpBgvxC",
        "level":2,
        "time":"April 14, 2021 09:03:29",
        "remoteAddr":"192.168.56.1",
        "user":"--",
        "app":"no app in context",
        "method":"POST",
        "url":"/login",
        "message":"Login failed: asdf (Remote IP: 192.168.56.1)",
        "userAgent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36",
        "version":"21.0.1.1"
    }

### Log field breakdown

- **reqId** (request id): any log lines related to a single request have the same value
- **level**: logged incident's level, always 1 in audit.log
- **time**: date and time (format and timezone can be configured in config.php)
- **remoteAddr**: the IP address of the user (if applicable – empty for occ commands)
- **user**: acting user's id (if applicable)
- **app**: affected app (always admin_audit in audit.log)
- **method**: HTTP method, for example GET, POST, PROPFIND, etc. – empty on occ calls
- **url**: request path (if applicable – empty on occ calls)
- **scriptName**: the PHP script name that handled the request
- **message**: event information message
- **userAgent**: user agent (if applicable – empty on occ calls)
- **exception**: full exception with trace (if applicable)
- **data**: additional structured data (if applicable)
- **version**: Nextcloud version at the time of request
- **clientReqId**: value of the `X-Request-Id` HTTP header sent by the client (only present when the header is set)
- **occ_command**: the occ command that was executed, as an array of up to two arguments (only present in CLI mode)
- **backtrace**: full PHP backtrace (only present when `log.backtrace` is enabled in config.php)

Empty values are written as two dashes: `--`.

## Admin audit log (Optional)

By enabling the **admin_audit** app, additional information about various events can be logged. The audit log supports all of the logging backends described above (file, syslog, systemd, errorlog).

### Default audit log location

When using the default `file` backend, the audit log is written to **audit.log** inside the directory configured by `datadirectory` in `config/config.php` (e.g. `/var/www/html/data/audit.log`).

You can override the path with the `logfile_audit` system config key:

    'logfile_audit' => '/var/log/nextcloud/audit.log',

### Dedicated audit logging configuration

The audit log backend can be configured independently from the main Nextcloud log using three dedicated keys in `config/config.php`:

**log_type_audit**  
The logging backend for audit events. Accepts the same values as `log_type`: `file`, `syslog`, `systemd`, or `errorlog`.

Defaults to `file`.

**logfile_audit**  
Path to the audit log file (only used when `log_type_audit` is `file`). When empty, the default `audit.log` in the data directory is used.

**syslog_tag_audit**  
The syslog identifier for audit messages (only used when `log_type_audit` is `syslog` or `systemd`). Defaults to the value of `syslog_tag`.

Example – send audit events to syslog instead of a file:

    'log_type_audit' => 'syslog',
    'syslog_tag_audit' => 'Nextcloud',
    'logfile_audit' => '',

### Log level interaction

The **admin_audit** app writes its messages at **INFO** level (`1`). Because the default system `loglevel` is **WARN** (`2`), audit messages are suppressed unless you explicitly lower the system log level or add a conditional override.

The recommended approach is to add a `log.condition` entry that forces DEBUG-level logging for the `admin_audit` app context, without affecting other apps:

    'log.condition' => [
        'apps' => ['admin_audit'],
    ],

This ensures audit events are always written regardless of the global `loglevel` setting.

### Integrating into the web interface

The built-in **logreader** app (which provides *Administration settings → Logging*) only reads the file-based `nextcloud.log`. By default the audit log is written to a separate `audit.log` file, so audit entries will not appear in the web interface.

If you want audit events to appear in the logreader, point `logfile_audit` at the same file as `nextcloud.log`:

    'log.condition' => [
        'apps' => ['admin_audit'],
    ],
    'logfile_audit' => '/var/www/html/data/nextcloud.log',

> **提示**
>
> Adjust the path above to match your actual `datadirectory` location. This merges audit entries into the main log file; the separate `audit.log` will no longer be written.

### Configuring through admin_audit app settings (legacy)

Previously the audit log file was defined via app config. This setting is still read as a fallback when `logfile_audit` is not set in `config/config.php`, but it is considered a **legacy** parameter. The system config key should be preferred for new installations.

    occ config:app:set admin_audit logfile --value=/var/log/nextcloud/audit.log

## Workflow log

The **workflowengine** app records events related to Nextcloud Flow (automated workflows configured under *Administration settings → Flow*). By default, these events are written to `flow.log` inside the data directory.

The path of the workflow log can be changed with:

    occ config:app:set workflowengine logfile --value=/var/log/nextcloud/flow.log

To disable workflow logging entirely, redirect the output to `/dev/null`:

    occ config:app:set workflowengine logfile --value=/dev/null

## Temporary overrides

You can override the config.php log level for `occ` commands as [documented here](/link/937).


# OAuth2

Nextcloud allows connecting external services (for example Moodle) to your Nextcloud. This is done via `OAuth2`. See [RFC6749](https://tools.ietf.org/html/rfc6749) for the OAuth2 specification.

> **提示**
>
> Nextcloud supports only confidential clients.

## Add an OAuth2 Application

Head over to your Administrator Security Settings. Here you can add a new `OAuth2` client.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/oauth2-settings.png)

Enter the name of your application and provide a redirection url. You should now have a Client Identifier and Secret. Enter those into your `OAuth2` client.

Please provide the OAuth2 application the following details:

- Authorization endpoint: `https://cloud.example.org/apps/oauth2/authorize`
- Token endpoint: `https://cloud.example.org/apps/oauth2/api/v1/token`

Note that you must include `index.php` if pretty URL is not configured - i.e. `https://cloud.example.org/index.php/apps/oauth2/api/v1/token`.

## The access token

The access token obtained is a so called Bearer token. Which means that for request to the Nextcloud server you will have to send the proper authorization header.

Authorization: Bearer \<TOKEN\>

Note that apache by default strips this. Make sure you have `mod_headers`, `mod_rewrite` and `mod_env` enabled.

## Security considerations

Nextcloud `OAuth2` implementation currently does not support scoped access. This means that every token has full access to the complete account including read and write permission to the stored files. It is essential to store the `OAuth2` tokens in a safe way!

Without scopes and restrictable access it is not recommended to use a Nextcloud instance as a user authentication service.

## Skipping pre-login warning

In Nextcloud default `OAuth2` flow, a confirmation step is shown before login if the user is not yet logged-in, and a second one is shown after login. To skip the pre-login one for a trusted application, the configuration option `skipAuthPickerApplications` can be set through occ:

    sudo -E -u www-data php occ config:app:set oauth2 skipAuthPickerApplications --type array --value '["myapplication"]'


# Reverse proxy

Nextcloud can be run through a reverse proxy, which can cache static assets such as images, CSS or JS files, move the load of handling HTTPS to a different server or load balance between multiple servers.

## Defining trusted proxies

For security, you must explicitly define the proxy servers that Nextcloud is to trust. Connections from trusted proxies will be specially treated to get the real client information, for use in access control and logging. Parameters are configured in `config/config.php`

Set the `trusted_proxies` parameter as an array of:

- IPv4 addresses
- IPv4 ranges in CIDR notation
- IPv6 addresses
- IPv6 ranges in CIDR notation

to define the servers Nextcloud should trust as proxies. This parameter provides protection against client spoofing, and you should secure those servers as you would your Nextcloud server.

A reverse proxy can define HTTP headers with the original client IP address, and Nextcloud can use those headers to retrieve that IP address. Nextcloud uses the de-facto standard header 'X-Forwarded-For' by default, but this can be configured with the **forwarded_for_headers** parameter. This parameter is an array of PHP lookup strings, for example 'X-Forwarded-For' becomes 'HTTP_X_FORWARDED_FOR'. Incorrectly setting this parameter may allow clients to spoof their IP address as visible to Nextcloud, even when going through the trusted proxy! The correct value for this parameter is dependent on your proxy software.

## Overwrite parameters

The automatic hostname, protocol or webroot detection of Nextcloud can fail in certain reverse proxy situations. This configuration allows the automatic detection to be manually overridden. If Nextcloud fails to automatically detect the hostname, protocol or webroot you can use the **overwrite** parameters inside the `config/config.php`.

- `overwritehost` set the hostname of the proxy. You can also specify a port.
- `overwriteprotocol` set the protocol of the proxy. You can choose between the two options **http** and **https**.
- `overwritewebroot` set the absolute web path of the proxy to the Nextcloud folder.
- `overwritecondaddr` overwrite the values dependent on the remote address. The value must be a **regular expression** of the IP addresses of the proxy. This is useful when you use a reverse SSL proxy only for https access and you want to use the automatic detection for http access.
- `overwrite.cli.url` the base URL for any URLs which are generated within Nextcloud using any kind of command line tools. For example, the value set here will be used by the notifications area.

Leave the value empty or omit the parameter to keep the automatic detection.

## Service Discovery

The redirects for CalDAV or CardDAV does not work if Nextcloud is running behind a reverse proxy. The recommended solution is that your reverse proxy does the redirects.

### Apache2

    RewriteEngine On
    RewriteRule ^/\.well-known/carddav https://%{SERVER_NAME}/remote.php/dav/ [R=301,L]
    RewriteRule ^/\.well-known/caldav https://%{SERVER_NAME}/remote.php/dav/ [R=301,L]

Thanks to [@ffried](https://github.com/ffried) for apache2 example.

### Traefik 1

Using Docker labels: :

    traefik.frontend.redirect.permanent: 'true'
    traefik.frontend.redirect.regex: 'https://(.*)/.well-known/(?:card|cal)dav'
    traefik.frontend.redirect.replacement: 'https://$$1/remote.php/dav'

Using traefik.toml: :

    [frontends.frontend1.redirect]
      regex = "https://(.*)/.well-known/(?:card|cal)dav"
      replacement = "https://$1/remote.php/dav
      permanent = true

Thanks to [@pauvos](https://github.com/pauvos) and [@mrtumnus](https://github.com/mrtumnus) for traefik examples.

### Traefik 2

Using Docker labels: :

    - "traefik.http.routers.nextcloud.middlewares=nextcloud_redirectregex@docker"
    - "traefik.http.middlewares.nextcloud_redirectregex.redirectregex.permanent=true"
    - "traefik.http.middlewares.nextcloud_redirectregex.redirectregex.regex=https://(.*)/.well-known/(?:card|cal)dav"
    - "traefik.http.middlewares.nextcloud_redirectregex.redirectregex.replacement=https://$${1}/remote.php/dav"

Using a TOML file: :

    [http.middlewares]
      [http.middlewares.nextcloud-redirectregex.redirectRegex]
        permanent = true
        regex = "https://(.*)/.well-known/(?:card|cal)dav"
        replacement = "https://${1}/remote.php/dav"

### HAProxy

    acl url_discovery path /.well-known/caldav /.well-known/carddav
    http-request redirect location /remote.php/dav/ code 301 if url_discovery

### NGINX

If using nginx as Nextcloud's webserver from behind another nginx reverse proxy, put this only in the reverse proxy's configuration. :

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

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

    location ^~ /.well-known {
        return 301 $scheme://$host/index.php$uri;
    }

When using NGINX Proxy Manager, the entry `proxy_hide_header Upgrade;` must be added in the *"Advanced Settings"* of the proxy host under *"Custom Nginx Configuration"*, otherwise mobile devices (iPad, iPhone etc.) will simply receive the Error Message "Connection Closed".

### Caddy

    subdomain.example.com {
        redir /.well-known/carddav /remote.php/dav/ 301
        redir /.well-known/caldav /remote.php/dav/ 301

        reverse_proxy {$NEXTCLOUD_HOST:localhost}
    }

### Pomerium

    - from: https://subdomain.example.com
      path: /.well-known/carddav
      redirect:
        path_redirect: /remote.php/dav/
    - from: https://subdomain.example.com
      path: /.well-known/caldav
      redirect:
        path_redirect: /remote.php/dav/

Thanks to [@JeffMatson](https://github.com/JeffMatson) for Pomerium example.

## Examples

### Nextcloud behind a reverse proxy (subdirectory)

If your Nextcloud is served at a subdirectory, for example **https://example.com/nextcloud**, behind a reverse proxy with IP address **10.0.0.1** that terminates TLS, set the following parameters inside `config/config.php`:

    <?php
    $CONFIG = array (
      'trusted_proxies'   => ['10.0.0.1'],
      'overwriteprotocol' => 'https',
      'overwritewebroot'  => '/nextcloud',
      'overwrite.cli.url' => 'https://example.com/nextcloud',
    );

> **提示**
>
> `overwritehost` is not needed in most setups — Nextcloud will read the hostname from the `Host` header forwarded by the proxy. Only set it if you need to force a specific hostname regardless of the incoming request. Leave any parameter unset or empty to keep the automatic detection.

### Nextcloud accessible via multiple domains / conditional overwrite

If Nextcloud is reachable both directly (HTTP) and through a reverse proxy (HTTPS), or through multiple proxies serving different public domains, use `overwritecondaddr` to apply the overwrite parameters only when requests arrive from a specific proxy IP address. Requests that do not originate from that proxy will use automatic detection.

In the example below, the overwrite parameters are applied only when requests come from the proxy at **10.0.0.1**, which serves Nextcloud as **https://public.example.com**:

    <?php
    $CONFIG = array (
      'trusted_proxies'   => ['10.0.0.1'],
      'overwritehost'     => 'public.example.com',
      'overwriteprotocol' => 'https',
      'overwritecondaddr' => '^10\.0\.0\.1$',
      'overwrite.cli.url' => 'https://public.example.com',
    );

> **提示**
>
> `overwritecondaddr` takes a regular expression matching the remote address of the proxy. When set, the overwrite parameters are only applied if the remote address matches. This is useful when the same Nextcloud instance is accessible both with and without a reverse proxy, or when different proxies serve the instance under different hostnames.

### Multiple trusted domains and share link URLs

When multiple entries are listed in `trusted_domains`, Nextcloud accepts requests on all of them and generates URLs based on the hostname of each incoming request. This means share links, download URLs, and notification links will reflect whichever hostname was used at the time they were copied.

A share link copied while accessing Nextcloud via an internal hostname (e.g. `cloud.local`) will contain that hostname and will not be reachable by users on a different network who only have access to the public hostname (e.g. `cloud.example.com`).

To ensure all generated URLs always use a single canonical hostname, set `overwritehost` and `overwrite.cli.url` unconditionally:

    <?php
    $CONFIG = array (
      'trusted_domains'   => ['cloud.local', 'cloud.example.com'],
      'overwritehost'     => 'cloud.example.com',
      'overwriteprotocol' => 'https',
      'overwrite.cli.url' => 'https://cloud.example.com',
    );

> **提示**
>
> Unlike the `overwritecondaddr` pattern above, this applies the overwrite to every request regardless of origin. Use this when you want one authoritative public URL for all generated links, even when the instance is also reachable internally under a different hostname.

# Text app

## Disable rich workspaces globally

Rich workspaces can be disabled globally by the admin by setting the following config option to 0 (default is 1):

    occ config:app:set text workspace_available --value=0

## Default file extension

The default file extension can be changed to txt in order to always create plain text files (default is md):

    occ config:app:set text default_file_extension --value=txt

## Disable rich text editing

Rich text editing can be turned off globally to always open markdown files in their raw format, without rendering of the formatting (default is 1):

    occ config:app:set text rich_editing_enabled --value=0

## File encodings

Text can automatically detect encodings of files and will convert them to UTF-8 when saving. Due to the variety of encodings, not all of them can be detected, however you can configure a list of encodings and in which priority they should be detected using the php `mbstring.detect_order` setting in your php.ini:

    mbstring.detect_order = ASCII,JIS,UTF-8,SJIS,EUC-JP

# Theming

The theming feature lets you customize the look and feel of your Nextcloud instance to match your organization's design (or - if for personal use - your own style). You can replace the Nextcloud logo and background images with your own assets, customize colors and slogans, and add dedicated legal and privacy links.

Theme customization is provided by the shipped and always-enabled `theming` app. Use the **Theming** section within the *Administration settings* menu to access all theming-related settings.

## Customize the appearance of Nextcloud

You can change the following aspects of your instance's appearance:

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/theming1.png)

- **Name** (e.g., ACME Inc. Cloud).
- **Web link** (e.g., <https://acme.inc/>).
- **Slogan**.
- **Primary color**: Used for important buttons, checkboxes, and folder icons.
- **Background color**: Used when no image is set; header bar icon color is also derived from this.
- **Logo**: Appears in the header and on the login page (default size: 62x34 px).
- **Background and login image**: Sets the page background.

![](https://docs.cocobook.com/uploads/images/gallery/2026-10/theming2.png)

- **Additional legal links**: Legal notice and privacy policy.
- **Custom header logo and favicon**: Optionally override the auto-generated favicon based on your logo.
- **Disable user theming**: Prevent users from changing backgrounds and colors. Toggle this to enforce your custom theme.

## Configure theming via CLI

You can also configure theming using the `occ theming:config` command.

Available settings include:

- name, url, imprintUrl, privacyUrl, slogan, background_color, primary_color. Example: `occ theming:config name "My Example Cloud"`
- background, logo, favicon, logoheader. Example: `occ theming:config logo /tmp/mylogo.png`
- disable-user-theming (yes/no). Example: `occ theming:config disable-user-theming yes`

> **提示**
>
> Images must be read from a local file on the Nextcloud server.

To use a color (instead of an image) for the background:

    occ theming:config background_color "#0082c9"
    occ theming:config background backgroundColor

## Icon theming

Based on your settings, Nextcloud will automatically generate favicons and a header logo using your logo and theme color.

This requires:

> - The PHP `imagick` module.
> - SVG support for imagick (e.g., `libmagickcore-7.q16-10-extra` on Debian 13 and `libmagickcore-6.q16-7-extra` on Ubuntu 24.04).

> **提示**
>
> In the advanced options of the theming app, you can set a custom favicon if you do not want to use auto-generated resources or install the above dependencies.

## Branded clients

> **提示**
>
> Nextcloud GmbH - the company that employs Nextcloud's core maintainers - offers branding services, providing sync clients (mobile and desktop) that use your corporate identity and are pre-configured for your users. For more information on advanced branding and enterprise support offerings, [contact Nextcloud GmbH](https://nextcloud.com/enterprise/).

The theming app supports changing the URLs for the mobile apps (Android and iOS) that appear when users access the web interface from mobile devices. By default, these links point to the official Nextcloud apps, but you can set them to branded versions.

Set custom app links using the `occ` command:

    occ config:app:set theming AndroidClientUrl --value "https://play.google.com/store/apps/details?id=com.nextcloud.client"
    occ config:app:set theming iTunesAppId --value "1125420102"
    occ config:app:set theming iOSClientUrl --value "https://itunes.apple.com/us/app/nextcloud/id1125420102?mt=8"


# Using the occ command

Nextcloud's `occ` command (origins from "ownCloud Console") is Nextcloud's command-line interface. You can perform many common server operations with `occ`, such as installing and upgrading Nextcloud, manage users, encryption, passwords, LDAP setting, and more.

`occ` is in the `nextcloud/` directory; for example `/var/www/nextcloud` on Ubuntu Linux. `occ` is a PHP script. **You must run it as your HTTP user** to ensure that the correct permissions are maintained on your Nextcloud files and directories.

## Running occ

You must run `occ` as your HTTP user so that the file ownership and permissions on your Nextcloud data directory stay consistent with the web server.

The HTTP user is different on the various Linux distributions:

- The HTTP user and group in Debian/Ubuntu is www-data.
- The HTTP user and group in Fedora/CentOS is apache.
- The HTTP user and group in Arch Linux is http.
- The HTTP user in openSUSE is wwwrun, and the HTTP group is www.

> **提示**
>
> APCu is disabled by default for the command-line mode of PHP, which can cause issues with Nextcloud's `occ` command. Please make sure you set the `apc.enable_cli` parameter to `1` in your PHP CLI's `php.ini` configuration file or append `--define apc.enable_cli=1` each time you invoke `occ` - e.g.:
>
>     sudo -u www-data php --define apc.enable_cli=1 occ config:list system
>
> If you fail to do this, you will receive output such as the following:
>
>     An unhandled exception has been thrown:
>     OCP\HintException: [0]: Memcache \OC\Memcache\APCu not available for local cache (Is the matching PHP module installed and enabled?)

If your HTTP server is configured to use a different PHP version than the default (/usr/bin/php), `occ` should be run with the same version. For example, in CentOS 6.5 with SCL-PHP70 installed, the command looks like this:

    sudo -u apache /opt/rh/php70/root/usr/bin/php /var/www/html/nextcloud/occ

> **提示**
>
> Although the following examples make use of the `sudo -u ... /path/to/php /path/to/occ` method, your environment may require use of a different wrapper utility than `sudo` to execute the command as the appropriate user. Other common wrappers:
>
> - `su --command '/path/to/php ...' username` -- Note here that the target user specification comes at the end, and the command to execute is specified first.
> - `runuser --user username -- /path/to/php ...` -- This wrapper might be used in container contexts (ex: Docker / `arm32v7/nextcloud`) where both `sudo` and `su` wrapper utilities cannot be used.

Running `occ` with no options lists all commands and options, like this example on Ubuntu:

    sudo -E -u www-data php occ
    Nextcloud version 19.0.0

    Usage:
     command [options] [arguments]

    Options:
     -h, --help            Display this help message
     -q, --quiet           Do not output any message
     -V, --version         Display this application version
         --ansi            Force ANSI output
         --no-ansi         Disable ANSI output
     -n, --no-interaction  Do not ask any interactive question
         --no-warnings     Skip global warnings, show command output only
     -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output,
                           2 for more verbose output and 3 for debug

    Available commands:
     check                 check dependencies of the server
                           environment
     help                  Displays help for a command
     list                  Lists commands
     status                show some status information
     upgrade               run upgrade routines after installation of
                           a new release. The release has to be
                           installed before.

This is the same as `sudo -E -u www-data php occ list`.

Run it with the `-h` option for syntax help:

    sudo -E -u www-data php occ -h

Display your Nextcloud version:

    sudo -E -u www-data php occ -V
      Nextcloud version 19.0.0

Query your Nextcloud server status:

    sudo -E -u www-data php occ status
      - installed: true
      - version: 19.0.0.12
      - versionstring: 19.0.0
      - edition:

`occ` has options, commands, and arguments. Options and arguments are optional, while commands are required. The syntax is:

    occ [options] command [arguments]

Get detailed information on individual commands with the `help` command, like this example for the `maintenance:mode` command:

    sudo -E -u www-data php occ help maintenance:mode
    Usage:
     maintenance:mode [options]

    Options:
         --on              enable maintenance mode
         --off             disable maintenance mode
     -h, --help            Display this help message
     -q, --quiet           Do not output any message
     -V, --version         Display this application version
         --ansi            Force ANSI output
         --no-ansi         Disable ANSI output
     -n, --no-interaction  Do not ask any interactive question
         --no-warnings     Skip global warnings, show command output only
     -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output,
                           2 for more verbose output and 3 for debug

The `status` command from above has an option to define the output format. The default is plain text, but it can also be `json`:

    sudo -E -u www-data php occ status --output=json
    {"installed":true,"version":"19.0.0.9","versionstring":"19.0.0","edition":""}

or `json_pretty`:

    sudo -E -u www-data php occ status --output=json_pretty
    {
       "installed": true,
       "version": "19.0.0.12",
       "versionstring": "19.0.0",
       "edition": ""
    }

This output option is available on all list and list-like commands: `status`, `check`, `app:list`, `config:list`, `encryption:status` and `encryption:list-modules`

### Environment variables

`sudo` does not forward environment variables by default. You can prepend the variable and use the `-E` switch to pass it through:

    NC_debug=true sudo -E -u www-data php occ status

Alternatively, `export` the variable first:

    export NC_debug=true
    sudo -E -u www-data php occ status

## Enabling autocompletion

> **提示**
>
> Command autocompletion currently only works if the user you use to execute the occ commands has a profile. `www-data` in most cases is `nologon` and therefore **cannot** use this feature.

Autocompletion is available for bash (and bash based consoles). To enable it, you have to run **one** of the following commands:

    # BASH ~4.x, ZSH
    source <(/var/www/html/nextcloud/occ _completion --generate-hook)

    # BASH ~3.x, ZSH
    /var/www/html/nextcloud/occ _completion --generate-hook | source /dev/stdin

    # BASH (any version)
    eval $(/var/www/html/nextcloud/occ _completion --generate-hook)

This will allow you to use autocompletion with the full path `/var/www/html/nextcloud/occ <tab>`.

If you also want to use autocompletion on occ from within the directory without using the full path, you need to specify `--program occ` after the `--generate-hook`.

If you want the completion to apply automatically for all new shell sessions, add the command to your shell's profile (eg. `~/.bash_profile` or `~/.zshrc`).

## Limitations in maintenance mode

In maintenance mode, apps are not loaded[^1], so commands from apps are unavailable. Commands integrated into Nextcloud server are available in maintenance mode.

We discourage the use of maintenance mode unless the command explicitly prompts you to do so or unless the commands' documentation explicitly states that maintenance mode should be used.

A command may use events to communicate with other apps. An app can only react to an event when loaded. Example: The command user:delete deletes a user account. UserDeletedEvent is emitted. Calendar app implements an event listener to delete user data[^2]. In maintenance mode, the Calendar app is not loaded, and hence the user data not deleted.

## Debugging

Every `occ` command accepts the standard Symfony Console verbosity flags:

- `-v` — normal output (errors, warnings, and key messages)
- `-vv` — verbose output (additional progress detail)
- `-vvv` — debug output (full trace, useful for diagnosing command failures)

Example:

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

To also enable debug-level log output from Nextcloud itself, set the `NC_loglevel` environment variable:

    NC_loglevel=0 sudo -E -u www-data php occ status

See [Logging](/link/932) for more on log levels.

## Command reference

- [Apps, background jobs & config commands](/link/938)
- [DAV & database commands](/link/939)
- [Encryption commands](/link/940)
- [Files commands](/link/941)
- [LDAP commands](/link/942)
- [OCM commands](/link/943)
- [User & group commands](/link/944)
- [System & maintenance commands](/link/945)

[^1]: Exception: [The settings app is loaded](https://github.com/nextcloud/server/blob/75f17b60945e15effc3eea41393eef2b13937226/lib/base.php#L780)

[^2]: [Calendar app event listener for UserDeletedEvent](https://github.com/nextcloud/calendar/blob/87e8586971a8676dc15a90f0cd969274678b7009/lib/Listener/UserDeletedListener.php)


# Apps, background jobs & config commands

## Apps commands

The `app` commands list, enable, and disable apps:

    app
     app:install      install selected app
     app:disable      disable an app
     app:enable       enable an app
     app:getpath      get an absolute path to the app directory
     app:list         list all available apps
     app:update       update an app or all apps
     app:remove       disable and remove an app

Download and install an app:

    sudo -E -u www-data php occ app:install twofactor_totp

Install but don't enable:

    sudo -E -u www-data php occ app:install --keep-disabled twofactor_totp

Install regardless of the Nextcloud version requirement:

    sudo -E -u www-data php occ app:install --force twofactor_totp

List all of your installed apps, and show whether they are enabled or disabled:

    sudo -E -u www-data php occ app:list

List all of your installed and enabled (flag `--enabled`) or disabled (flag `--disabled`) apps:

    sudo -E -u www-data php occ app:list --enabled

List non-shipped installed apps only:

    sudo -E -u www-data php occ app:list --shipped false

Enable an app, for example the External Storage Support app:

    sudo -E -u www-data php occ app:enable files_external
    files_external enabled

Enable an app regardless of the Nextcloud version requirement:

    sudo -E -u www-data php occ app:enable --force files_external
    files_external enabled

Enable an app for specific groups of users (i.e. restrict an app so only specific groups can see and use them):

    sudo -E -u www-data php occ app:enable --groups admin --groups sales files_external
    files_external enabled for groups: admin, sales

Enable multiple apps simultaneously:

    sudo -E -u www-data php occ app:enable app1 app2 app3
    app1 enabled
    app2 enabled
    app3 enabled

Disable an app:

    sudo -E -u www-data php occ app:disable files_external
    files_external disabled

Disable and remove an app:

    sudo -E -u www-data php occ app:remove files_external
    files_external disabled
    files_external 1.21.0 removed

Remove an app, but keep the app data:

    sudo -E -u www-data php occ app:remove --keep-data files_external
    files_external 1.21.0 removed

You can get the full filepath to an app:

    sudo -E -u www-data php occ app:getpath notifications
    /var/www/nextcloud/apps/notifications

To update an app, for instance Contacts:

    sudo -E -u www-data php occ app:update contacts

To update all apps:

    sudo -E -u www-data php occ app:update --all

To show available update(s) without updating:

    sudo -E -u www-data php occ app:update --showonly

To update an app to an unstable release, for instance News:

    sudo -E -u www-data php occ app:update --allow-unstable news

## Background jobs selector

Use the `background` commands to select which scheduler you want to use for controlling background jobs. This is the same as using the **Cron** section on your Nextcloud Admin page:

    background
     background:cron       Set background jobs to cron mode
     background:ajax       Set background jobs to ajax mode
     background:webcron    Set background jobs to webcron mode

Example:

    sudo -E -u www-data php occ background:cron
      Set mode for background jobs to 'cron'

The other two commands are:

- `background:ajax`
- `background:webcron`

See [Background jobs](/link/924) to learn more.

## Config commands

The `config` commands are used to configure the Nextcloud server:

    config
     config:app:delete      Delete an app config value
     config:app:get         Get an app config value
     config:app:set         Set an app config value
     config:import          Import a list of configs
     config:list            List all configs
     config:system:delete   Delete a system config value
     config:system:get      Get a system config value
     config:system:set      Set a system config value

While setting a configuration value, multiple options are available:

> - `--value=VALUE` change the configuration value
> - `--type=TYPE` change the type of the value. Use carefully; can break your instance
> - `--lazy|--no-lazy` set value as lazy
> - `--sensitive|--no-sensitive` set value as sensitive
> - `--update-only` only updates if a value is already stored

> **提示**
>
> See [Appconfig Concepts](https://docs.nextcloud.com/server/latest/developer_manual/digging_deeper/config/appconfig.html#concept-overview) to learn more about typed value, lazy and sensitive flag.

You can list all configuration values with one command:

    sudo -E -u www-data php occ config:list

By default, passwords and other sensitive data are omitted from the report, so the output can be posted publicly (e.g. as part of a bug report). In order to generate a full export of all configuration values the `--private` flag needs to be set:

    sudo -E -u www-data php occ config:list --private

The exported content can also be imported again to allow the fast setup of similar instances. The import command will only add or update values. Values that exist in the current configuration, but not in the one that is being imported are left untouched:

    sudo -E -u www-data php occ config:import filename.json

It is also possible to import remote files, by piping the input:

    sudo -E -u www-data php occ config:import < local-backup.json

> **提示**
>
> While it is possible to update/set/delete the versions and installation statuses of apps and Nextcloud itself, it is **not** recommended to do this directly. Use the `occ app:enable`, `occ app:disable` and `occ app:update` commands instead.

### Getting a single configuration value

These commands get the value of a single app or system configuration:

    sudo -E -u www-data php occ config:system:get version
    19.0.0.12

    sudo -E -u www-data php occ config:app:get activity installed_version
    2.2.1

### Setting a single configuration value

These commands set the value of a single app or system configuration:

    sudo -E -u www-data php occ config:system:set logtimezone
    --value="Europe/Berlin"
    System config value logtimezone set to Europe/Berlin

    sudo -E -u www-data php occ config:app:set files_sharing
    incoming_server2server_share_enabled --value="yes"
    Config value incoming_server2server_share_enabled for app files_sharing set to yes

The `config:system:set` command creates the value, if it does not already exist. To update an existing value, set `--update-only`:

    sudo -E -u www-data php occ config:system:set doesnotexist --value="true"
    --type=boolean --update-only
    Value not updated, as it has not been set before.

Note that in order to write a Boolean, float, or integer value to the configuration file, you need to specify the type on your command. This applies only to the `config:system:set` command. The following values are known:

- `boolean`
- `float`
- `integer`
- `json`
- `null`
- `string` (default)

When you want to e.g. disable the maintenance mode run the following command:

    sudo -E -u www-data php occ config:system:set maintenance --value=false --type=boolean
    Nextcloud is in maintenance mode - no app have been loaded
    System config value maintenance set to boolean false

### Setting an array configuration value

Some configurations (e.g. the trusted domain setting) are an array of data. In this case, `config:system:get` for this key will return multiple values:

    sudo -E -u www-data php occ config:system:get trusted_domains
    localhost
    nextcloud.local
    sample.tld

To set one of multiple values, you need to specify the array index as the second `name` in the `config:system:set` command, separated by a space. For example, to replace `sample.tld` with `example.com`, `trusted_domains => 2` needs to be set:

    sudo -E -u www-data php occ config:system:set trusted_domains 2 --value=example.com
    System config value trusted_domains => 2 set to string example.com

    sudo -E -u www-data php occ config:system:get trusted_domains
    localhost
    nextcloud.local
    example.com

Alternatively, you can set the entry array at once by using the `json` type:

    sudo -E -u www-data php occ config:system:set trusted_domains --type json --value '["nextcloud.local","example.com"]'
    System config value trusted_domains set to json ["nextcloud.local","example.com"]

    sudo -E -u www-data php occ config:system:get trusted_domains
    nextcloud.local
    example.com

### Setting a hierarchical configuration value

Some configurations use hierarchical data. For example, the settings for the Redis cache would look like this in the `config.php` file:

    'redis' => array(
      'host' => '/var/run/redis/redis.sock',
      'port' => 0,
      'dbindex' => 0,
      'password' => 'secret',
      'timeout' => 1.5,
    )

Setting such hierarchical values works similarly to setting an array value above. For this Redis example, use the following commands:

    sudo -E -u www-data php occ config:system:set redis host \
    --value=/var/run/redis/redis.sock
    sudo -E -u www-data php occ config:system:set redis port --value=0
    sudo -E -u www-data php occ config:system:set redis dbindex --value=0
    sudo -E -u www-data php occ config:system:set redis password --value=secret
    sudo -E -u www-data php occ config:system:set redis timeout --value=1.5

Alternatively, you can set the entry configuration at once by using the `json` type:

    sudo -E -u www-data php occ config:system:set redis --type json --value '{"host":"/var/run/redis/redis.sock","port":0,"dbindex":0,"password":"secret","timeout":1.5}'

### Deleting a single configuration value

These commands delete the configuration of an app or system configuration:

    sudo -E -u www-data php occ config:system:delete maintenance:mode
    System config value maintenance:mode deleted

    sudo -E -u www-data php occ config:app:delete appname provisioning_api
    Config value provisioning_api of app appname deleted

The delete command will by default not complain if the configuration was not set before. If you want to be notified in that case, set the `--error-if-not-exists` flag:

    sudo -E -u www-data php occ config:system:delete doesnotexist
    --error-if-not-exists
    System config value doesnotexist could not be deleted because it did not exist


# DAV & database commands

## DAV commands

The `dav` commands manage addressbooks, calendars, calendar subscriptions, absences, and related data:

    dav
     dav:absence:get                 get the out-of-office absence settings for a user
     dav:absence:set                 set the out-of-office absence settings for a user
     dav:clear-calendar-unshares     clear calendar unshares for a user
     dav:clear-contacts-photo-cache  clear cached contact photos
     dav:create-addressbook          create a dav addressbook
     dav:create-calendar             create a dav calendar
     dav:create-subscription         create a dav subscription
     dav:delete-calendar             delete a dav calendar
     dav:delete-subscription         delete a calendar subscription for a user
     dav:fix-missing-caldav-changes  insert missing calendarchanges rows for existing events
     dav:list-addressbooks           list all addressbooks of a user
     dav:list-calendar-shares        list all calendar shares for a user
     dav:list-calendars              list all calendars of a user
     dav:list-subscriptions          list all calendar subscriptions for a user
     dav:move-calendar               move a calendar from one user to another
     dav:remove-invalid-shares       remove invalid dav shares
     dav:retention:clean-up          delete CalDAV trash elements that are due for removal
     dav:send-event-reminders        send event reminder notifications
     dav:sync-birthday-calendar      synchronize the birthday calendar
     dav:sync-system-addressbook     synchronize users to the system addressbook
    calendar
     calendar:export                 export a calendar of a user
     calendar:import                 import a calendar to a user

### Manage addressbooks

#### dav:list-addressbooks

List all addressbooks for a user:

    sudo -E -u www-data php occ dav:list-addressbooks layla
    +-------------+----------+-----------------------------+-------------------+----------+
    | Database ID | URI      | Owner principal             | Owner displayname | Writable |
    +-------------+----------+-----------------------------+-------------------+----------+
    | contacts    | Contacts | principals/users/layla      | Layla Smith       |  ✓       |
    +-------------+----------+-----------------------------+-------------------+----------+

#### dav:create-addressbook

Create an addressbook for a user:

    sudo -E -u www-data php occ dav:create-addressbook layla work

### Manage calendars

#### dav:list-calendars

List all calendars for a user:

    sudo -E -u www-data php occ dav:list-calendars layla
    +----------+-------------+-----------------------------+-------------------+----------+
    | URI      | Displayname | Owner principal             | Owner displayname | Writable |
    +----------+-------------+-----------------------------+-------------------+----------+
    | personal | Personal    | principals/users/layla      | Layla Smith       |  ✓       |
    +----------+-------------+-----------------------------+-------------------+----------+

#### dav:list-calendar-shares

List all calendar shares for a user:

    sudo -E -u www-data php occ dav:list-calendar-shares layla
      User layla has no calendar shares

Use `--calendar-id` to filter results to a specific calendar.

#### dav:create-calendar

Create a calendar for a user:

    sudo -E -u www-data php occ dav:create-calendar layla holidays

#### dav:delete-calendar

Delete a named calendar for a user:

    sudo -E -u www-data php occ dav:delete-calendar layla holidays

Use `--birthday` to delete the birthday calendar instead of specifying a name. Use `-f` / `--force` to delete immediately instead of moving to the trashbin:

    sudo -E -u www-data php occ dav:delete-calendar --force layla holidays
    sudo -E -u www-data php occ dav:delete-calendar --birthday layla

#### dav:move-calendar

> **提示**
>
> Moving a calendar changes its existing share URLs.

Move a calendar from one user to another:

    sudo -E -u www-data php occ dav:move-calendar personal layla fred

Without `--force`, the command fails if the destination user already has a calendar with the same name, or if the calendar is shared with a group the destination user is not a member of.

Use `-f` / `--force` to proceed anyway: conflicting group shares are dropped, and if the calendar name is already taken at the destination a new name is tried automatically (`personal-1`, `personal-2`, up to ten attempts). The command fails if no free name is found within those attempts.

#### dav:clear-calendar-unshares

Clear stale calendar unshare records for a user. Useful when a user's calendar sharing state has become inconsistent:

    sudo -E -u www-data php occ dav:clear-calendar-unshares layla
      User layla has no calendar unshares

### Manage calendar subscriptions

#### dav:list-subscriptions

List all calendar subscriptions for a user:

    sudo -E -u www-data php occ dav:list-subscriptions layla
      User layla has no subscriptions

#### dav:create-subscription

Create a subscription calendar for a user:

    sudo -E -u www-data php occ dav:create-subscription layla "Astronomy Calendar" \
      webcal://cantonbecker.com/astronomy-calendar/astrocal.ics

Optionally pass a HEX color code for the calendar:

    sudo -E -u www-data php occ dav:create-subscription layla "Astronomy Calendar" \
      webcal://cantonbecker.com/astronomy-calendar/astrocal.ics "#ff5733"

If not set, the theming default color is used.

#### dav:delete-subscription

Delete a calendar subscription for a user:

    sudo -E -u www-data php occ dav:delete-subscription layla "Astronomy Calendar"

### Manage absences (out-of-office)

#### dav:absence:set

Set the out-of-office absence for a user. `first-day` and `last-day` are inclusive and formatted as `YYYY-MM-DD`.

- **short-message** — a brief one-liner displayed as the user's status next to their name across the UI while they are absent (e.g. in contacts, chat, and user lists).
- **message** — the full out-of-office text shown to users who try to reach the absent user.
- **replacement-user-id** — optional; a colleague to contact instead. Their display name is stored alongside the absence and shown to others.

<!-- -->

    sudo -E -u www-data php occ dav:absence:set layla 2026-05-01 2026-05-15 \
      "On leave" \
      "I am on leave until May 15. For urgent matters please contact my colleague."

To set an absence with a replacement user:

    sudo -E -u www-data php occ dav:absence:set layla 2026-05-01 2026-05-15 \
      "On leave" \
      "I am on leave. Please contact fred for urgent matters." \
      fred

#### dav:absence:get

Show the current absence settings for a user:

    sudo -E -u www-data php occ dav:absence:get layla
      Start day: 2026-05-01
      End day: 2026-05-15
      Short message: On leave
      Message: I am on leave until May 15. For urgent matters please contact my colleague.
      Replacement user: none
      Replacement display name: none

### Sync

#### dav:sync-system-addressbook

Synchronize all users to the [system address book](/link/1036):

    sudo -E -u www-data php occ dav:sync-system-addressbook
      Syncing users ...

#### dav:sync-birthday-calendar

Add birthdays from shared addressbooks to a user's calendar:

    sudo -E -u www-data php occ dav:sync-birthday-calendar layla
      Start birthday calendar sync for layla

### Maintenance

#### dav:fix-missing-caldav-changes

Restore missing calendar sync change records. If the `calendarchanges` table has lost data, clients may not sync correctly. Run for a single user, or omit the user ID to fix all users (may take some time on large instances):

    sudo -E -u www-data php occ dav:fix-missing-caldav-changes layla
    sudo -E -u www-data php occ dav:fix-missing-caldav-changes

#### dav:remove-invalid-shares

Remove invalid DAV shares created by a bug in a previous version:

    sudo -E -u www-data php occ dav:remove-invalid-shares

#### dav:retention:clean-up

Delete elements from the CalDAV trash that are past their retention period:

    sudo -E -u www-data php occ dav:retention:clean-up

#### dav:send-event-reminders

Send pending calendar event reminder notifications. By default, Nextcloud sends reminders via the background job. To use this command instead, switch the mode first:

    sudo -E -u www-data php occ config:app:set dav sendEventRemindersMode --value occ

Then call the command regularly via a dedicated cron job to ensure reminders are sent on time:

    sudo -E -u www-data php occ dav:send-event-reminders

See [../groupware/calendar](/link/1035) for the recommended cron schedule.

#### dav:clear-contacts-photo-cache

Clear all cached contact photos. Useful after a migration or if contact avatars are not displaying correctly:

    sudo -E -u www-data php occ dav:clear-contacts-photo-cache
      No cached contact photos found.

### Export and import calendars

#### calendar:export

Export a calendar to a file or standard output:

    sudo -E -u www-data php occ calendar:export layla personal --location /tmp/personal.ics

`--format` selects the output format (default: `ical`):

- `ical` — iCalendar (RFC 5545)
- `xcal` — XML iCalendar (RFC 6321)
- `jcal` — JSON iCalendar (RFC 7265)

`--location` sets the output file path. If omitted, output is written to standard output:

    sudo -E -u www-data php occ calendar:export layla personal --format xcal \
      --location /tmp/personal.xcal
    sudo -E -u www-data php occ calendar:export layla personal --format jcal

#### calendar:import

Import calendar entries into a user's calendar:

    sudo -E -u www-data php occ calendar:import layla personal /tmp/personal.ics

`--format` selects the input format (default: `ical`). Same values as `calendar:export`. If `location` is omitted, reads from standard input:

    sudo -E -u www-data php occ calendar:import --format xcal layla personal \
      /tmp/personal.xcal
    cat /tmp/personal.ics | sudo -E -u www-data php occ calendar:import layla personal

`--supersede` forces override of existing objects with the same UID.

Validation behaviour is controlled with `--validation`:

- `0` — no validation
- `1` — validate, skip invalid entries
- `2` — validate, fail on invalid entries

Error handling is controlled with `--errors`:

- `0` — continue on error (default)
- `1` — fail on first error

Use `--show-created`, `--show-updated`, `--show-skipped`, or `--show-errors` to see the UIDs of affected objects after import.

### Disable creation of example events

Disable the automatic creation of example events for new calendar users:

    sudo -E -u www-data php occ config:app:set dav create_example_event \
      --value=false --type=boolean

## Database commands

The `db` commands manage database schema, indices, and data conversions:

    db
     db:add-missing-columns          add missing optional columns to the database tables
     db:add-missing-indices          add missing indices to the database tables
     db:add-missing-primary-keys     add missing primary keys to the database tables
     db:convert-filecache-bigint     convert the ID columns of the filecache to BigInt
     db:convert-mysql-charset        convert charset of MySQL/MariaDB to utf8mb4
     db:convert-type                 convert the Nextcloud database to a different type
     db:schema:check                 compare the live database schema with the expected schema
     db:schema:expected              export the expected database schema for a fresh installation
     db:schema:export                export the current database schema

### Schema maintenance

#### db:add-missing-indices

Add any indices to the database that are defined in the schema but missing from the current installation. Run this after upgrades if performance has degraded or if prompted by the admin overview:

    sudo -E -u www-data php occ db:add-missing-indices
      Done.

Use `--dry-run` to preview the SQL statements without executing them:

    sudo -E -u www-data php occ db:add-missing-indices --dry-run

#### db:add-missing-columns

Add optional columns that are defined in the schema but missing from the current installation:

    sudo -E -u www-data php occ db:add-missing-columns
      Done.

Use `--dry-run` to preview the SQL statements without executing them.

#### db:add-missing-primary-keys

Add primary keys that are defined in the schema but missing from the current installation:

    sudo -E -u www-data php occ db:add-missing-primary-keys
      Done.

Use `--dry-run` to preview the SQL statements without executing them.

### Schema inspection

#### db:schema:check

> *New in version 35.0*

Compare the live database schema with the schema expected for the currently installed Nextcloud version:

    sudo -E -u www-data php occ db:schema:check
      The live database schema matches the expected schema.

The expected schema is generated from the migrations provided by Nextcloud core, all enabled apps, and any disabled apps whose code is still present. The command reports missing or unexpected tables, columns, and indexes. It also reports column properties that differ, such as the type, length, default value, or whether the column is nullable.

The command only inspects the schema and does not modify the database. It exits with status `0` if there are no findings for core or an enabled app, and status `1` otherwise. This makes it suitable for use in monitoring scripts. Findings that only concern a disabled app never affect the exit status. They are excluded from the plain output unless you add `-v`:

    sudo -E -u www-data php occ db:schema:check -v
      oc_example: column 'size' differs in: type, default
      Disabled apps (not affecting exit code):
      If the schema for a disabled app differs from what is expected, this might indicate the app was
      updated since it was disabled. Missing migrations will be applied once the app is enabled again.
        files_external:
          - oc_storages: missing column 'backend'

Specify a table name to limit the comparison to that table:

    sudo -E -u www-data php occ db:schema:check oc_filecache

Use the complete table name, including the configured database table prefix. Use `--output=json` or `--output=json_pretty` to produce machine-readable output. Unlike plain output, JSON output always includes every finding, including those for disabled apps. For example:

```console
$ sudo -E -u www-data php occ db:schema:check --output=json_pretty
[
    {
        "table": "oc_filecache",
        "type": "modified_column",
        "name": "size",
        "changes": [
            "type",
            "default"
        ],
        "app": null,
        "enabled": true
    },
    {
        "table": "oc_storages",
        "type": "missing_column",
        "name": "backend",
        "app": "files_external",
        "enabled": false
    },
    {
        "table": "oc_example",
        "type": "unexpected_table",
        "app": null,
        "enabled": true
    }
]
```

Each finding contains:

- `table` — the complete database table name.
- `type` — one of `missing_table`, `unexpected_table`, `missing_column`, `unexpected_column`, `modified_column`, `missing_index`, or `unexpected_index`.
- `name` — the affected column or index. This field is omitted for table findings.
- `changes` — the changed column properties. This field is only present when `type` is `modified_column`. Possible values include `type`, `length`, `precision`, `scale`, `nullable`, `default`, `autoincrement`, `unsigned`, `fixed`, and `comment`.
- `app` — the ID of the disabled app that owns the affected table, or `null` if the table belongs to core or an enabled app.
- `enabled` — `false` if the finding only concerns a disabled app and does not affect the exit status, `true` otherwise.

When the schemas match, JSON output contains an empty array.

> **提示**
>
> The expected schema does not account for all database-wide settings or defaults, so some reported differences may be valid. A table or other object still counts as unexpected if it belongs to an app that was disabled and then fully removed. Review each finding before changing the database.

The schema check also runs automatically after `occ upgrade`. Findings for core or an enabled app are displayed as warnings but do not cause the upgrade to fail; findings that only concern a disabled app are not shown here. For example, the following output may appear near the end of an upgrade:

```console
The database schema does not match what is expected for the installed version:
  - oc_filecache: column 'size' differs in: type, default
  - oc_filecache: missing index 'fs_storage_path_hash'
  - unexpected table 'oc_example'
Run "occ db:schema:check -v" for details.
```

Run `occ db:schema:check` separately to inspect the differences in plain (add `-v` to include disabled-app findings) or machine-readable format.

#### db:schema:export

Export the current database schema. Useful for debugging or comparing against the expected schema:

    sudo -E -u www-data php occ db:schema:export
      - oc_filecache:
        - columns:
          - checksum:
            - name: checksum
            - type: string

Limit output to a single table:

    sudo -E -u www-data php occ db:schema:export oc_filecache

Use `--sql` to output SQL `CREATE TABLE` statements instead of the default structured format. Use `--output=json_pretty` for machine-readable output.

#### db:schema:expected

Export the expected schema for a fresh installation of the current version. Compare this against `db:schema:export` to identify divergences caused by incomplete upgrades or manual changes:

    sudo -E -u www-data php occ db:schema:expected
    sudo -E -u www-data php occ db:schema:expected oc_filecache

Supports the same `--sql` and `--output` options as `db:schema:export`.

### Data conversions

#### db:convert-filecache-bigint

Convert the `filecache` table's ID columns from integer to BigInt. Required on large installations where file IDs have exceeded the integer limit. This command is non-destructive but may take time on large databases:

    sudo -E -u www-data php occ db:convert-filecache-bigint

#### db:convert-mysql-charset

Convert all MySQL or MariaDB tables to use `utf8mb4` (full Unicode, including emoji). Required for proper Unicode support. Run this once after switching to or upgrading MySQL/MariaDB:

    sudo -E -u www-data php occ db:convert-mysql-charset

#### db:convert-type

Convert the Nextcloud database from SQLite to MySQL, MariaDB, or PostgreSQL. SQLite is suitable for testing and single-user setups, but production servers with multiple users should use one of the other supported databases.

Requirements:

- The target database and its PHP connector must be installed.
- Login credentials for a database admin user.
- The database port number, if non-standard.

This example converts from SQLite to MySQL/MariaDB:

    sudo -E -u www-data php occ db:convert-type mysql oc_dbuser 127.0.0.1 oc_database

For a detailed walkthrough see [../configuration_database/db_conversion](/link/910).


# Encryption commands

The `encryption` commands manage server-side encryption, encryption keys, and encryption modules. The core commands are always available. Commands that operate on the encryption module itself (master key, key repair, legacy migration) require the **Encryption** app (`encryption`) to be enabled.

> **提示**
>
> For a full guide to configuring server-side encryption, see [../configuration_files/encryption_configuration](/link/966).

    encryption
     encryption:change-key-storage-root      change key storage root
     encryption:clean-orphaned-keys          scan the keys storage for orphaned keys and remove them
     encryption:decrypt-all                  disable server-side encryption and decrypt all files
     encryption:disable                      disable encryption
     encryption:disable-master-key           disable the master key and use per-user keys instead
     encryption:drop-legacy-filekey          scan the files for the legacy filekey format using RC4 and get rid of it
     encryption:enable                       enable encryption
     encryption:enable-master-key            enable the master key
     encryption:encrypt-all                  encrypt all files for all users
     encryption:fix-encrypted-version        fix the encrypted version if the encrypted file(s) are not downloadable
     encryption:fix-key-location             fix the location of encryption keys for external storage
     encryption:list-modules                 list all available encryption modules
     encryption:migrate-key-storage-format   migrate the format of the key storage to a newer format
     encryption:recover-user                 recover user data in case of password loss
     encryption:scan:legacy-format           scan the files for the legacy format
     encryption:set-default-module           set the encryption default module
     encryption:show-key-storage-root        show current key storage root
     encryption:status                       lists the current status of encryption

## Status and control

### encryption:status

Show whether encryption is enabled and which module is active:

    sudo -E -u www-data php occ encryption:status
      - enabled: false
      - defaultModule: OC_DEFAULT_MODULE

Use `--output=json_pretty` for machine-readable output.

### encryption:enable

Enable server-side encryption. The **Encryption** app must be enabled first and a default module must be configured:

    sudo -E -u www-data php occ app:enable encryption
    sudo -E -u www-data php occ encryption:enable
      Encryption enabled

      Default module: OC_DEFAULT_MODULE

### encryption:disable

Disable server-side encryption. This only disables the encryption flag — it does not decrypt any files:

    sudo -E -u www-data php occ encryption:disable
      Encryption disabled

To also decrypt all existing files, run `encryption:decrypt-all` afterwards.

## Encrypt and decrypt all data

### encryption:encrypt-all

Encrypt all files for all users. Encryption must be enabled before running this command. The command manages maintenance mode internally — do **not** enable maintenance mode first, as the command will fail if it is already active:

    sudo -E -u www-data php occ encryption:encrypt-all
      You are about to encrypt all files stored in your Nextcloud installation.
      Depending on the number of available files, and their size, this may take quite some time.
      Please ensure that no user accesses their files during this time!
      Note: The encryption module you use determines which files get encrypted.

      Do you really want to continue? (y/n)

The command requires an interactive terminal (TTY). If running inside a Docker container, use `docker exec -it`.

### encryption:decrypt-all

Decrypt all files for all users, or for a single user. The command manages maintenance mode internally — do **not** enable maintenance mode first:

    sudo -E -u www-data php occ encryption:decrypt-all
    sudo -E -u www-data php occ encryption:decrypt-all layla

When decrypting all users, server-side encryption is disabled automatically. When decrypting a single user, encryption remains enabled for others.

Depending on the encryption module in use, decryption may require:

- **Master key mode** — no extra credentials needed.
- **Per-user key mode** — the user must have enabled the recovery key on their personal settings page.

The command requires an interactive terminal (TTY). If running inside a Docker container, use `docker exec -it`.

## Encryption modules

### encryption:list-modules

List all available encryption modules. The active default module is marked with `[default*]`:

    sudo -E -u www-data php occ encryption:list-modules
      - OC_DEFAULT_MODULE: Default encryption module [default*]

### encryption:set-default-module

Set the default encryption module. Maintenance mode must be disabled:

    sudo -E -u www-data php occ encryption:set-default-module OC_DEFAULT_MODULE
      Set default module to "OC_DEFAULT_MODULE"

## Key storage

### encryption:show-key-storage-root

Show where encryption keys are stored:

    sudo -E -u www-data php occ encryption:show-key-storage-root
      Current key storage root:  default storage location (data/)

### encryption:change-key-storage-root

Move encryption keys to a different directory. The target directory must exist and be writable by the web server user before running the command:

    sudo -E -u www-data php occ encryption:change-key-storage-root /etc/nextcloud/keys
      Change key storage root from default storage location to /etc/nextcloud/keys
      Start to move keys:
      [============================]
      Key storage root successfully changed to /etc/nextcloud/keys

Omit the argument to reset the key storage root back to the default location (`data/`). The command will ask for confirmation:

    sudo -E -u www-data php occ encryption:change-key-storage-root
      No storage root given, do you want to reset the key storage root to the default location? (y/n)

### encryption:migrate-key-storage-format

Migrate the key storage to the current format (JSON-wrapped, re-encrypted with the server secret). Run this once after upgrading from an installation that used the legacy key format:

    sudo -E -u www-data php occ encryption:migrate-key-storage-format
      Updating key storage format
      Start to update the keys:
      [============================]
      Key storage format successfully updated

## Master key

The master key encrypts all user data with a single server-managed key. It is the recommended setup for new installations because it simplifies key management and enables admin-side decryption without per-user passwords. The master key is enabled by default when the Encryption app is first enabled.

Both commands are only available when the **Encryption** app is enabled.

> **注意**
>
> Switching between master key and per-user key mode is only safe on a **fresh installation with no existing encrypted data**. If you switch modes on an instance that already has encrypted files, those files will become permanently inaccessible: the new mode looks for keys that were never created for the existing data. **There is no recovery path.** Always run `encryption:decrypt-all` first if you need to change modes on an existing installation.

> **提示**
>
> Despite the warning shown by both commands ("no way to enable/disable it again"), the switch is technically reversible as long as no encrypted data exists yet. The warning is intended to convey that you cannot safely switch modes once users have data.

### encryption:enable-master-key

Enable the master key. Only use this on a **fresh installation with no existing encrypted data**. The command prompts for confirmation:

    sudo -E -u www-data php occ encryption:enable-master-key
      Master key successfully enabled.

### encryption:disable-master-key

Disable the master key and revert to per-user keys. Only use this on a **fresh installation with no existing encrypted data**. The command prompts for confirmation:

    sudo -E -u www-data php occ encryption:disable-master-key
      Master key successfully disabled.

Switching to per-user keys has the following consequences:

- **Performance** — per-user key operations are slower. Each user's key must be derived individually on every file access.
- **Password loss means data loss** — without the master key there is no admin-side decryption path. Each user must enable the recovery key on their personal settings page *before* losing their password. Without it, `encryption:recover-user` cannot help and the files cannot be recovered.
- **Admin decryption is no longer possible** — admins cannot decrypt or access a user's files without that user's password or a pre-set recovery key.

## Maintenance and repair

### encryption:clean-orphaned-keys

Scan the key storage for keys that no longer have a corresponding file and remove them. Optionally limit the scan to a single user:

    sudo -E -u www-data php occ encryption:clean-orphaned-keys
    sudo -E -u www-data php occ encryption:clean-orphaned-keys layla

When orphaned keys are found, the command lists them and asks interactively whether to delete all, specific ones, or none:

    sudo -E -u www-data php occ encryption:clean-orphaned-keys layla
      Key storage scan for layla
      ==========================

      Orphaned key found: /layla/files_encryption/keys/files/old-doc.pdf/OC_DEFAULT_MODULE/fileKey
      Do you want to delete all orphaned keys? (y/n)

If no orphaned keys are found, the command exits silently.

### encryption:fix-encrypted-version

Fix the encrypted version counter in the file cache when encrypted files cannot be downloaded. Requires **master key** encryption.

Run for a single user:

    sudo -E -u www-data php occ encryption:fix-encrypted-version layla
      Verifying the content of file "/layla/files/Documents/report.pdf"
      The file "/layla/files/Documents/report.pdf" is: OK

Run for all users:

    sudo -E -u www-data php occ encryption:fix-encrypted-version --all
      Processing files for layla
      Verifying the content of file "/layla/files/Documents/report.pdf"
      The file "/layla/files/Documents/report.pdf" is: OK

When a broken file is found, the command tries decrementing and then incrementing the encrypted version counter until the file can be read:

    Attempting to fix the path: "/layla/files/Documents/broken.pdf"
    Decrement the encrypted version to 2
    Fixed the file: "/layla/files/Documents/broken.pdf" with version 2

Use `-p` / `--path` to limit the scan to a specific directory:

    sudo -E -u www-data php occ encryption:fix-encrypted-version layla --path="/Documents"

### encryption:fix-key-location

Fix the location of encryption keys for files on external storage mounts. Run this when users cannot access files on external storage after a migration:

    sudo -E -u www-data php occ encryption:fix-key-location layla
      Migrating key for /layla/files/ExternalDrive/report.pdf ✓

Use `--dry-run` to list files that need migration without making any changes:

    sudo -E -u www-data php occ encryption:fix-key-location --dry-run layla
      /layla/files/ExternalDrive/report.pdf needs migration

### encryption:recover-user

Recover a user's files after a password loss. Only available in **per-user key** mode (not applicable when master key is enabled). The user must have enabled the recovery key in their personal settings before the password was lost.

The command prompts for the recovery key password and the new login password:

    sudo -E -u www-data php occ encryption:recover-user layla
      Please enter the recovery key password:
      Please enter the new login password for the user:
      Start to recover users files... This can take some time...Done.

## Legacy migration

### encryption:drop-legacy-filekey

Scan all files for the legacy RC4 filekey format and migrate them to the current format. Requires **master key** encryption. Files not migrated by this command will be migrated automatically on their next write. Running this command upfront also converts old base64-encoded files to binary format, saving approximately 33% disk space:

    sudo -E -u www-data php occ encryption:drop-legacy-filekey
      Scanning all files for legacy filekey
      Scanning all files for layla
      All scanned files are properly encrypted.

### encryption:scan:legacy-format

Scan all files for the legacy encryption format. Use this to determine whether any files still need migration before disabling legacy format compatibility:

    sudo -E -u www-data php occ encryption:scan:legacy-format
      Scanning all files for legacy encryption
      Scanning all files for layla
      All scanned files are properly encrypted. You can disable the legacy compatibility mode.

If files using the legacy format are found, their paths are listed. Run `encryption:drop-legacy-filekey` to migrate them.


# Files commands

The `occ` commands in this section cover day-to-day file management, storage maintenance, and sharing administration. They let you scan and repair the file cache, move or delete files on behalf of users, manage trash and version history, configure external storage mounts, inspect object store contents, and verify app integrity from the command line.

Several sections require specific apps to be enabled. All of the following are shipped with Nextcloud and can be enabled in the Apps menu:

- **Trash bin** commands require the **Deleted files** app (`files_trashbin`) — enabled by default
- **File versions** commands require the **Versions** app (`files_versions`) — enabled by default
- **Federation sync** requires the **Federation** app (`federation`) — enabled by default
- **External storage** commands require the **External storage support** app (`files_external`) — not enabled by default

## File operations

    files
     files:cleanup                        remove file cache entries with no matching storage entry
     files:copy                           copy a file or folder
     files:delete                         delete a file or folder
     files:get                            get the contents of a file
     files:mount:list                     list all mounts for a user
     files:mount:refresh                  refresh the list of mounts for a user
     files:move                           move a file or folder
     files:put                            write content to a file
     files:mkdir                          create a new folder
     files:touch                          update the modified date of a file or folder
     files:reminders                      list file reminders
     files:repair-tree                    repair malformed filesystem tree structures
     files:sanitize-filenames             rename files that do not match the current filename constraints
     files:scan                           rescan the filesystem
     files:scan-app-data                  rescan the AppData folder
     files:transfer-ownership             transfer all files and shares from one user to another
     files:windows-compatible-filenames   toggle enforcement of Windows-compatible filenames

### files:cleanup

Remove all file cache entries that have no matching entry in the storage table. Run this after removing orphaned storage records or after a migration that left the file cache in an inconsistent state:

    sudo -E -u www-data php occ files:cleanup

### files:copy

Copy a file or folder within Nextcloud. Source and target accept either a Nextcloud path or a numeric file ID:

    sudo -E -u www-data php occ files:copy /layla/files/Photos \
      /layla/files/Photos-backup

If the target path already exists and is a folder, the source is copied into it (standard cp behaviour). Use `--no-target-directory` / `-T` to overwrite the target folder instead:

    sudo -E -u www-data php occ files:copy -T /layla/files/Photos \
      /layla/files/Photos-backup

If the target exists the command asks for confirmation. Use `--force` / `-f` to skip the prompt and suppress type-mismatch warnings.

### files:delete

Delete a file or folder:

    sudo -E -u www-data php occ files:delete /layla/files/Documents/old-draft.pdf

The command asks for confirmation before deleting. Use `--force` / `-f` to skip the prompt.

If the path points to the root of a share received by a user, the command asks whether to unshare (remove the user's access) rather than delete the underlying file:

    sudo -E -u www-data php occ files:delete /layla/files/Shared-Folder
      /layla/files/Shared-Folder in a shared file, do you want to unshare
      the file from layla instead of deleting the source file? [Y/n]

When the file is accessible by multiple users, the command lists all affected users and asks for confirmation before proceeding.

If the trashbin is enabled, you can use `--skip-trash` to bypass the trashbin and permanently delete the files directly.

### files:get

Download a file from Nextcloud to a local path. The source argument accepts either a Nextcloud path or a numeric file ID:

    sudo -E -u www-data php occ files:get /layla/files/Documents/report.pdf \
      /tmp/report.pdf

Omit the output path (or pass `-`) to write to standard output:

    sudo -E -u www-data php occ files:get /layla/files/Documents/report.pdf -

> **注意**
>
> Writing binary files to a terminal can corrupt your terminal session. Nextcloud will refuse to write binary content to STDOUT unless you explicitly pass `-` as the output path.

### files:mount:list

List all registered mounts for a user, including mount point, storage ID, provider, and whether the mount is still actively provided:

    sudo -E -u www-data php occ files:mount:list layla
    /layla/: local::home/nextcloud/data/layla/files
            - provider: OC\Files\Mount\LocalRootMountProvider
            - storage id: 1
            - root id: 1

Stale mounts (registered in the cache but no longer provided) are marked with `registered but no longer provided`.

### files:mount:refresh

Re-register all currently active mounts for a user in the mount cache. Useful after mount configuration changes that were not automatically picked up:

    sudo -E -u www-data php occ files:mount:refresh layla
      Registered 3 mounts

### files:move

Move a file or folder within Nextcloud:

    sudo -E -u www-data php occ files:move \
      /layla/files/Documents/draft.pdf \
      /layla/files/Documents/Archive/draft.pdf

If the target already exists, the command asks for confirmation. Use `--force` / `-f` to skip the prompt. If source and target are different types (file vs. folder), the target is deleted before the move; the command refuses if the target is a mount root or is not deletable.

### files:put

Upload a local file to Nextcloud. The target argument accepts either a Nextcloud path or a numeric file ID of an existing file:

    sudo -E -u www-data php occ files:put /tmp/report.pdf \
      /layla/files/Documents/report.pdf

Read from standard input by passing `-` as the source:

    cat /tmp/report.pdf | sudo -E -u www-data php occ files:put - \
      /layla/files/Documents/report.pdf

Any missing parent folder for the specified destination will be created automatically.

### files:mkdir

Create a new empty folder, parent folders will automatically be created if needed:

    sudo -E -u www-data php occ files:mkdir /layla/files/Documents/Reports

### files:touch

Update the last modified date of a file or folder. The target argument accepts either a Nextcloud path or a numeric file ID of an existing file:

    sudo -E -u www-data php occ files:touch  /layla/files/Documents/report.pdf

Instead of using the current time, you can specify the modified date to use with the `--date` option. Accepted formats are: ISO8601, "YYYY-MM-DD" and Unix time in seconds.:

    sudo -E -u www-data php occ files:touch  /layla/files/Documents/report.pdf \
      --date 2026-07-15

### files:reminders

List all file reminders across all users, or for a specific user:

    sudo -E -u www-data php occ files:reminders
    +-------+---------+-------------------------------------------+---------------------------+
    | User  | File Id | Path                                      | Due Date (UTC)            |
    +-------+---------+-------------------------------------------+---------------------------+
    | layla | 42      | /layla/files/Documents/report.pdf         | 2026-05-01T09:00:00+00:00 |
    +-------+---------+-------------------------------------------+---------------------------+

    sudo -E -u www-data php occ files:reminders layla

Use `--output=json_pretty` for machine-readable output.

### files:repair-tree

Repair entries in the file cache whose stored path does not match the path derived from their parent. This can cause files to appear in the wrong location: listing a folder shows the file, but accessing it by path fails. The command resets each affected entry to its correct path:

    sudo -E -u www-data php occ files:repair-tree

### files:sanitize-filenames

Rename files that do not comply with the current filename constraints (for example, after enabling [Windows-compatible filenames](/link/974)). Run for all users or a specific user:

    sudo -E -u www-data php occ files:sanitize-filenames
    sudo -E -u www-data php occ files:sanitize-filenames layla

Invalid characters are replaced with a space, underscore, or dash — whichever is allowed by the current constraints. Use `--char-replacement` to specify the replacement character when none of those defaults are permitted:

    sudo -E -u www-data php occ files:sanitize-filenames \
      --char-replacement=_ layla

Use `--dry-run` to preview the renames without making changes:

    sudo -E -u www-data php occ files:sanitize-filenames --dry-run

### files:scan

Scan for new or changed files and update the file cache. Run for all users, a specific user, or a specific path:

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

Use `--path` to limit the scan to a specific directory. The path must include the user ID and `files/`:

    sudo -E -u www-data php occ files:scan --path="/layla/files/Photos"

The `--path`, `--all`, and `[user_id]` options are mutually exclusive; only one may be given at a time.

Additional options:

- `--generate-metadata` — generate metadata (e.g. EXIF data) for scanned files
- `--unscanned` — only scan files marked as not yet fully scanned (useful when triggering the scan that the background job would otherwise run)
- `--shallow` — do not scan folders recursively
- `--home-only` — skip external storages and shares, scan only the home storage
- `--quiet` — suppress output; without this option, statistics are shown after the scan
- `--output=json_pretty` — machine-readable output

Use `-v` to see each file as it is processed. Verbosity levels `-vv` and `-vvv` are silently capped to `-v`.

A background job runs every 10 minutes to scan files with an unknown size in the file cache, so routine rescans are handled automatically. Use this command when you need an immediate rescan — for example after copying files directly into the data directory, after a migration, or to investigate file cache inconsistencies. The background scan can be disabled by setting `'files_no_background_scan' => true` in `config.php`.

### files:scan-app-data

Rescan the `appdata` directory and update the file cache for files shared between users (avatar images, file previews, cached CSS, etc.):

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

Limit the scan to a specific appdata subdirectory:

    sudo -E -u www-data php occ files:scan-app-data preview

Unlike `files:scan`, there is no background job that automatically rescans appdata. Run this command manually when the appdata file cache may have become inconsistent; for example, after restoring appdata from a backup, after manually moving or copying files into the appdata directory, or when previews or avatars are not displaying correctly despite the underlying files being present on disk.

### files:transfer-ownership

Transfer all files and shares from one user to another. Useful before removing a user account:

    sudo -E -u www-data php occ files:transfer-ownership layla fred

The transferred files appear in a subdirectory inside the destination user's home folder.

> **提示**
>
> Unless server-side encryption is enabled, the command initialises the destination user's file system if they have not yet logged in. If the destination user's data directory cannot be written to, the command reports: `unable to rename, destination directory is not writable`.

If the destination user's home is empty, use `--move` to move files directly into the root without creating a subdirectory:

    sudo -E -u www-data php occ files:transfer-ownership --move layla fred

Transfer only a specific folder with `--path`:

    sudo -E -u www-data php occ files:transfer-ownership \
      --path="Documents/Project" layla fred

Incoming shares (files shared with the source user) are not transferred by default because ownership remains with the original sharer. Transfer them with `--transfer-incoming-shares=1`:

    sudo -E -u www-data php occ files:transfer-ownership \
      --transfer-incoming-shares=1 layla fred

Set `'transferIncomingShares' => true` in `config.php` to always transfer incoming shares. The command-line option takes precedence:

    sudo -E -u www-data php occ files:transfer-ownership \
      --transfer-incoming-shares=0 layla fred

Users may also transfer files selectively via the web interface. See [user documentation](/link/811) for details.

### files:windows-compatible-filenames

Toggle enforcement of [Windows-compatible filenames](/link/974):

    sudo -E -u www-data php occ files:windows-compatible-filenames --enable
    sudo -E -u www-data php occ files:windows-compatible-filenames --disable

After enabling, run `files:sanitize-filenames` to rename any existing files that do not comply.

## Object store

    files
     files:object:delete                  delete an object from the object store
     files:object:get                     get the contents of an object
     files:object:info                    get the metadata of an object
     files:object:list                    list all objects in the object store
     files:object:orphans                 list objects in the object store with no matching database entry
     files:object:put                     write a file to the object store

These commands operate directly on the underlying object storage (S3, Swift, etc.) used as Nextcloud's primary storage. They bypass the file cache and normal access controls.

> **注意**
>
> These commands manipulate objects directly in the object store. Writing or deleting objects that belong to existing files will corrupt those files. Use them only for debugging or recovery, never for routine file management.

### files:object:list

List all objects in the object store. Requires the configured object store to support metadata listing:

    sudo -E -u www-data php occ files:object:list
    +------------+--------+-------------------------------+
    | URN        | Size   | Last modified                 |
    +------------+--------+-------------------------------+
    | urn:oid:1  | 512    | 2026-01-01T00:00:00+00:00     |
    | urn:oid:42 | 204800 | 2026-04-01T12:00:00+00:00     |
    +------------+--------+-------------------------------+

Use `--bucket` / `-b` if the bucket cannot be determined from the config. Use `--output=json_pretty` for machine-readable output.

### files:object:get

Download an object from the object store to a local file. Pass `-` as the output path to write to standard output:

    sudo -E -u www-data php occ files:object:get urn:oid:42 /tmp/recovered.pdf
    sudo -E -u www-data php occ files:object:get urn:oid:42 -

### files:object:info

Show metadata (size, MIME type, last-modified date) for an object:

    sudo -E -u www-data php occ files:object:info urn:oid:42
      - size: 200 KB
      - mimetype: application/pdf
      - mtime: 2026-04-01T12:00:00+00:00

Use `--output=json_pretty` for machine-readable output.

### files:object:put

Upload a local file to the object store under the given object name. Read from standard input by passing `-`:

    sudo -E -u www-data php occ files:object:put /tmp/data.bin urn:oid:42
    sudo -E -u www-data php occ files:object:put - urn:oid:42

If the object already corresponds to a file in the database, the command warns and asks for confirmation before overwriting. To update a file safely, use `files:put` with the file ID instead.

### files:object:delete

Delete an object from the object store:

    sudo -E -u www-data php occ files:object:delete urn:oid:42

If the object belongs to a file in the database, the command warns that deleting it will corrupt the file and shows the file ID so you can use `files:delete` instead for a clean removal.

### files:object:orphans

List objects in the object store that have no matching entry in the file cache database. These are objects that Nextcloud no longer tracks and may be safe to remove after investigation:

    sudo -E -u www-data php occ files:object:orphans

Use `--output=json_pretty` for machine-readable output. Requires the object store to support metadata listing.

## Preview

    preview
     preview:cleanup                      remove all generated preview files

### preview:cleanup

Remove all generated preview files. Useful after changing preview configuration (sizes, quality, or supported file types), or on installations using object storage as primary storage where the preview folder cannot be deleted manually:

    sudo -E -u www-data php occ preview:cleanup
      Previews removed

After running this command, Nextcloud regenerates previews on demand as users access files.

See [Previews configuration](/link/970) for preview settings.

## Trash bin

    trashbin
     trashbin:cleanup                     permanently delete all files in the trash for a user
     trashbin:expire                      expire trash items that exceed the configured retention period
     trashbin:size                        show or set the target trash bin size

### trashbin:size

Show the current trash bin size target:

    sudo -E -u www-data php occ trashbin:size
      Default size: default (50% of available space)

Show the effective size for a specific user:

    sudo -E -u www-data php occ trashbin:size --user layla
      default (50% of available space)

Set the global default target size. Accepts human-readable sizes:

    sudo -E -u www-data php occ trashbin:size 10GB

> **提示**
>
> Changing the global default immediately triggers a cleanup of existing trash bins. A user's trash may temporarily exceed the configured size until the user next moves a file to trash.

Set a per-user target size:

    sudo -E -u www-data php occ trashbin:size --user layla 2GB

### trashbin:cleanup

Permanently delete all files in the trash bin for one or more users, or for all users:

    sudo -E -u www-data php occ trashbin:cleanup layla
      Remove deleted files of   layla

    sudo -E -u www-data php occ trashbin:cleanup layla fred
    sudo -E -u www-data php occ trashbin:cleanup --all-users

Use `--verbose` to see the amount of data freed per user. Either a user ID or `--all-users` must be given; the two cannot be combined.

### trashbin:expire

Expire trash items that exceed the configured retention period, as defined by `trashbin_retention_obligation` in `config.php`:

    sudo -E -u www-data php occ trashbin:expire layla
    sudo -E -u www-data php occ trashbin:expire

> **提示**
>
> This command only runs when a custom retention period is configured. If Nextcloud is set to auto-expiration (the default), the command exits with an informational message and does nothing; auto-expiration is handled by the background job instead.

See [Controlling file versions and aging](/link/971) for retention configuration.

## File versions

    versions
     versions:cleanup                     delete stored file versions
     versions:expire                      expire file versions that exceed the configured retention period

### versions:cleanup

Delete stored file versions for one or more users, all users, or a specific path:

    sudo -E -u www-data php occ versions:cleanup layla
      Delete versions of   layla

    sudo -E -u www-data php occ versions:cleanup layla fred
    sudo -E -u www-data php occ versions:cleanup

Use `--path` to limit deletion to a specific directory. The path must include the user ID and `files/`:

    sudo -E -u www-data php occ versions:cleanup \
      --path="/layla/files/Documents" layla

### versions:expire

Expire file versions that exceed the configured retention period, as defined by `versions_retention_obligation` in `config.php`:

    sudo -E -u www-data php occ versions:expire layla
    sudo -E -u www-data php occ versions:expire

> **提示**
>
> This command only runs when a custom retention period is configured. If Nextcloud is set to auto-expiration (the default), the command exits and does nothing; auto-expiration is handled by the background job instead.

See [Controlling file versions and aging](/link/971) for retention configuration.

## File sharing

    sharing
     sharing:cleanup-remote-storages      clean up remote storage entries with no matching federated share
     sharing:delete-orphan-shares         delete shares where the owner no longer has file access
     sharing:expiration-notification      notify share initiators when a share expires the next day
     sharing:fix-share-owners             fix share owner after a legacy transfer-ownership operation
    share
     share:list                           list available shares

### share:list

List shares across the instance. Without options, lists all shares:

    sudo -E -u www-data php occ share:list
    +----+-------+-------------------------------+------+-------+-----------+-------+
    | id | file  | source-path                   | type | owner | recipient | by    |
    +----+-------+-------------------------------+------+-------+-----------+-------+
    | 1  | 42    | /layla/files/Documents/rep... | user | layla | fred      | layla |
    +----+-------+-------------------------------+------+-------+-----------+-------+

Filter options:

- `--owner` — only shares owned by a specific user
- `--recipient` — only shares with a specific recipient
- `--by` — only shares initiated by a specific user
- `--file` — only shares of a specific file (path or file ID)
- `--parent` — only shares of files inside a specific folder
- `--recursive` — combine with `--parent` to include nested shares
- `--type` — filter by share type: `user`, `group`, `link`, `email`, `remote`, `room`, `deck`
- `--status` — only shares with a specific status

Use `--output=json_pretty` for machine-readable output.

### sharing:cleanup-remote-storages

Remove `shared::` storage entries from the database that have no matching entry in the `shares_external` table. These orphaned entries are left behind when a federated share is removed without proper cleanup:

    sudo -E -u www-data php occ sharing:cleanup-remote-storages
      5 remote storage(s) need(s) to be checked
      3 remote share(s) exist
      deleting shared::abc123 [14] ... deleted 1 storage

Use `--dry-run` to preview what would be deleted without making changes:

    sudo -E -u www-data php occ sharing:cleanup-remote-storages --dry-run

### sharing:delete-orphan-shares

Delete shares where the owner has lost access to the shared file or the file no longer exists:

    sudo -E -u www-data php occ sharing:delete-orphan-shares
      /layla/files/Documents/report.pdf owned by layla
        file still exists but the share owner lost access to it,
        run occ info:file 42 for more information about the file
      Delete 1 orphan shares? [y/N]

Use `--force` / `-f` to delete without prompting. Filter to shares by a specific user with `--owner` or to shares with a specific user with `--with`:

    sudo -E -u www-data php occ sharing:delete-orphan-shares --owner layla
    sudo -E -u www-data php occ sharing:delete-orphan-shares --with fred

### sharing:expiration-notification

Send in-app notifications to share initiators whose shares expire the following day. Run this daily via a cron job to ensure timely notifications:

    sudo -E -u www-data php occ sharing:expiration-notification

### sharing:fix-share-owners

Fix the recorded owner of shares that were broken by a `transfer-ownership` operation performed on an older Nextcloud version. Use `--dry-run` to preview changes:

    sudo -E -u www-data php occ sharing:fix-share-owners --dry-run
      Share with id 7 (target: /fred/files/report.pdf) can be
      updated to owner layla

    sudo -E -u www-data php occ sharing:fix-share-owners
      Share with id 7 (target: /fred/files/report.pdf) updated to owner layla
      No broken shares detected

## Federation sync

    federation
     federation:sync-addressbooks         synchronize address books of all federated clouds

### federation:sync-addressbooks

Synchronize the shared address books of all federated Nextcloud servers. Federated servers share user address books so that usernames auto-complete in share dialogs. Run this command to trigger an immediate sync rather than waiting for the background job:

    sudo -E -u www-data php occ federation:sync-addressbooks

## Files external

    files_external
     files_external:applicable            manage applicable users and groups for a mount
     files_external:backends              show available authentication and storage backends
     files_external:config                manage backend configuration for a mount
     files_external:create                create a new mount configuration
     files_external:delete                delete an external mount
     files_external:dependencies          check for missing dependencies needed for mounting external storages
     files_external:export                export mount configurations
     files_external:import                import mount configurations
     files_external:list                  list configured admin or personal mounts
     files_external:notify                listen for active update notifications for a configured external mount
     files_external:option                manage mount options for a mount
     files_external:scan                  scan an external storage for changed files
     files_external:verify                verify mount configuration

Manage Nextcloud's external storage mounts. Commands that read or write mount configuration operate on the same data as the **External Storages** admin settings page.

### files_external:list

List configured mounts. Without arguments, lists admin-level mounts:

    sudo -E -u www-data php occ files_external:list
    +----+------------------+-----------+--------------+---------+--------+-------+
    | ID | Mount Point      | Storage   | Auth. Type   | Config  | Status | Users |
    +----+------------------+-----------+--------------+---------+--------+-------+
    | 1  | /shared/data     | amazons3  | builtin      | valid   | ok     | all   |
    +----+------------------+-----------+--------------+---------+--------+-------+

List personal mounts for a specific user:

    sudo -E -u www-data php occ files_external:list layla

Use `--output=json_pretty` for machine-readable output. Add `--show-password` to include credentials in the output.

### files_external:create

Create a new mount configuration:

    sudo -E -u www-data php occ files_external:create \
      /shared/photos amazons3 builtin::builtin \
      --config bucket=my-nextcloud-photos \
      --config region=eu-central-1 \
      --config key=AKIAIOSFODNN7EXAMPLE \
      --config secret=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

Arguments:

- **mount-point** — the path inside Nextcloud (e.g. `/shared/photos`)
- **storage-backend** — the storage type identifier (e.g. `amazons3`, `sftp`, `smb`, `owncloud`)
- **auth-backend** — the authentication method (e.g. `builtin::builtin`, `password::sessioncredentials`)

Use `files_external:backends` to list all available storage and authentication backends.

For a personal mount, specify the user with `--user`:

    sudo -E -u www-data php occ files_external:create \
      /my-s3 amazons3 builtin::builtin \
      --config bucket=layla-bucket \
      --user layla

### files_external:config

Read or write individual backend configuration options for a mount. Use the mount ID from `files_external:list`:

    sudo -E -u www-data php occ files_external:config 1 get bucket
      my-nextcloud-photos

    sudo -E -u www-data php occ files_external:config 1 set bucket new-bucket-name

### files_external:applicable

Manage which users and groups have access to a mount:

    sudo -E -u www-data php occ files_external:applicable 1 --add-user layla
    sudo -E -u www-data php occ files_external:applicable 1 --add-group milliways
    sudo -E -u www-data php occ files_external:applicable 1 --remove-user layla
    sudo -E -u www-data php occ files_external:applicable 1 --remove-group milliways

A mount with no users or groups assigned is available to all users.

### files_external:option

Read or write mount options such as `enable_sharing` or `filesystem_check_changes`:

    sudo -E -u www-data php occ files_external:option 1 get enable_sharing
    sudo -E -u www-data php occ files_external:option 1 set enable_sharing true

### files_external:verify

Test the configuration of a mount and report whether a connection can be established:

    sudo -E -u www-data php occ files_external:verify 1
      +----------+---------+
      | Result   | Message |
      +----------+---------+
      | success  |         |
      +----------+---------+

Pass additional configuration key-value pairs (e.g. credentials) with `--config` when the stored configuration is incomplete:

    sudo -E -u www-data php occ files_external:verify 1 \
      --config user=layla --config password=secret

### files_external:delete

Delete a mount configuration:

    sudo -E -u www-data php occ files_external:delete 1

The command asks for confirmation. Use `--yes` to skip the prompt.

### files_external:scan

Scan an external storage for changed files and update the file cache. Useful for storage backends that do not support active change notifications:

    sudo -E -u www-data php occ files_external:scan 1

For mounts that use session credentials, pass them with `--user` and `--password`:

    sudo -E -u www-data php occ files_external:scan 1 \
      --user layla --password secret

### files_external:export

Export all admin mounts to JSON:

    sudo -E -u www-data php occ files_external:export > mounts.json

Export personal mounts for a specific user:

    sudo -E -u www-data php occ files_external:export layla > layla-mounts.json

Use the exported JSON with `files_external:import` to replicate the configuration on another Nextcloud instance.

### files_external:import

Import mount configurations from a JSON file produced by `files_external:export`:

    sudo -E -u www-data php occ files_external:import mounts.json

Import as personal mounts for a specific user:

    sudo -E -u www-data php occ files_external:import \
      --user layla layla-mounts.json

### files_external:backends

List all available storage and authentication backends:

    sudo -E -u www-data php occ files_external:backends

Filter by type:

    sudo -E -u www-data php occ files_external:backends storage
    sudo -E -u www-data php occ files_external:backends authentication

Use `--output=json_pretty` to inspect the full capability and configuration schema for each backend.

### files_external:notify

Listen for active change notifications from an external mount that supports push-based update events (e.g. SMB with inotify):

    sudo -E -u www-data php occ files_external:notify 1

This is a long-running process; run it under a process supervisor or in a dedicated systemd service.

### files_external:dependencies

Check for any missing PHP extensions or system packages required to use the configured external storage backends:

    sudo -E -u www-data php occ files_external:dependencies

## Trashbin

> **提示**
>
> These commands are only available when the "Deleted files" app (`files_trashbin`) is enabled.

    trashbin
     trashbin:cleanup  remove deleted files
     trashbin:expire   expire deleted files according to the configured retention policy
     trashbin:restore  restore all deleted files according to the given filters
     trashbin:size     configure or show the target trashbin size

### trashbin:cleanup

Remove all deleted files for all users, or for specific users:

    sudo -E -u www-data php occ trashbin:cleanup
    sudo -E -u www-data php occ trashbin:cleanup layla fred

### trashbin:expire

Apply the configured trashbin retention policy and remove files that have exceeded the maximum retention age. Runs for all users by default, or for specific users:

    sudo -E -u www-data php occ trashbin:expire
    sudo -E -u www-data php occ trashbin:expire layla

### trashbin:restore

Restore deleted files according to the given filters. Restore all deleted files for all users:

    sudo -E -u www-data php occ trashbin:restore --all-users

Restore deleted files for specific users:

    sudo -E -u www-data php occ trashbin:restore layla

Use `--scope` to limit the restore to a specific scope; one of `user`, `groupfolders`, or `all` (default: `user`):

    sudo -E -u www-data php occ trashbin:restore --scope groupfolders layla

Use `--since` and `--until` to limit the restore to files deleted within a given time window. Both options accept any format supported by PHP `strtotime`:

    sudo -E -u www-data php occ trashbin:restore --scope all \
      --since "2026-08-01 11:55:22" --until "2026-08-02 01:33:00" layla

Use `--dry-run` to simulate the restore without making any changes:

    sudo -E -u www-data php occ trashbin:restore --dry-run --all-users

> **提示**
>
> Use `-v` or `-vv` to see more detail about the restore process and why some files may be skipped.

### trashbin:size

Show or configure the target trashbin size. When called without arguments, shows the current configured size:

    sudo -E -u www-data php occ trashbin:size

Set the default trashbin size for all users:

    sudo -E -u www-data php occ trashbin:size 10GB

Set the trashbin size for a specific user:

    sudo -E -u www-data php occ trashbin:size --user layla 5GB

## Versions

> **提示**
>
> These commands are only available when the "Versions" app (`files_versions`) is enabled.

    versions
     versions:cleanup  delete file versions
     versions:expire   expire file versions according to the configured retention policy

### versions:cleanup

Delete all file versions for all users, or for specific users. Use `--path` to limit deletion to a specific path:

    sudo -E -u www-data php occ versions:cleanup
    sudo -E -u www-data php occ versions:cleanup layla
    sudo -E -u www-data php occ versions:cleanup layla --path="/files/Documents"

### versions:expire

Apply the configured version retention policy and remove versions that have exceeded the maximum retention age. Runs for all users by default, or for specific users:

    sudo -E -u www-data php occ versions:expire
    sudo -E -u www-data php occ versions:expire layla

## Integrity check

    integrity
     integrity:check-app                  check integrity of an app using a signature
     integrity:check-core                 check core integrity using a signature
     integrity:sign-app                   sign an app using a private key

Apps that carry a `Featured` tag must be code-signed by Nextcloud. Unsigned featured apps cannot be installed.

### integrity:check-app

Check the integrity of an app against its signature:

    sudo -E -u www-data php occ integrity:check-app contacts

Check all installed apps at once:

    sudo -E -u www-data php occ integrity:check-app --all

When the app passes, the command produces no output (use `-v` to confirm). When it fails, each integrity error is listed with details. Use `--path` to point to a non-standard app location:

    sudo -E -u www-data php occ integrity:check-app \
      --path=/var/www/nextcloud/apps/myapp myapp

Apps without a `signature.json` file are skipped with an informational message.

### integrity:check-core

Check the integrity of Nextcloud core against its signature:

    sudo -E -u www-data php occ integrity:check-core

### integrity:sign-app

Sign an app with a private key before distribution. Requires the key and certificate obtained through the Nextcloud signing process:

    sudo -E -u www-data php occ integrity:sign-app \
      --path=/path/to/app \
      --privateKey=/path/to/myapp.key \
      --certificate=/path/to/myapp.crt

See [Code Signing](https://docs.nextcloud.com/server/latest/developer_manual/app_publishing_maintenance/code_signing.html) in the Developer manual for the full signing process.


# LDAP commands

## LDAP commands

> **提示**
>
> These commands are only available when the "LDAP user and group backend" app (`user_ldap`) is enabled.

These LDAP commands appear only when you have enabled the LDAP app. Then you can run the following LDAP commands with `occ`:

    ldap
     ldap:check-user               checks whether a user exists on LDAP.
     ldap:check-group              checks whether a group exists on LDAP.
     ldap:create-empty-config      creates an empty LDAP configuration
     ldap:delete-config            deletes an existing LDAP configuration
     ldap:search                   executes a user or group search
     ldap:set-config               modifies an LDAP configuration
     ldap:show-config              shows the LDAP configuration
     ldap:show-remnants            shows which users are not available on
                                   LDAP anymore, but have remnants in
                                   Nextcloud.
     ldap:test-config              tests an LDAP configuration
     ldap:test-user-settings       runs tests and show information about user
                                   related LDAP settings

### ldap:search

Search for an LDAP user, using this syntax

> sudo -E -u www-data php occ <ldap:search> \[--group\] \[--offset="..."\] \[--limit="..."\] search

Searches will match at the beginning of the attribute value only. This example searches for givenNames that start with "rob":

    sudo -E -u www-data php occ ldap:search "rob"

This will find robbie, roberta, and robin. Broaden the search to find, for example, `jeroboam` with the asterisk wildcard:

    sudo -E -u www-data php occ ldap:search "*rob"

User search attributes are set with `ldap:set-config` (below). For example, if your search attributes are `givenName` and `sn` you can find users by first name + last name very quickly. For example, you'll find Terri Hanson by searching for `te ha`. Trailing whitespaces are ignored.

### ldap:check-user

Check if an LDAP user exists. This works only if the Nextcloud server is connected to an LDAP server:

    sudo -E -u www-data php occ ldap:check-user robert

Use `--update` to update the account fields from LDAP:

    sudo -E -u www-data php occ ldap:check-user --update robert

Will not run a check when it finds a disabled LDAP connection. This prevents users that exist on disabled LDAP connections from being marked as deleted. If you know for certain that the user you are searching for is not in one of the disabled connections, and exists on an active connection, use the `--force` option to force it to check all active LDAP connections:

    sudo -E -u www-data php occ ldap:check-user --force robert

You can also use `--all-seen-users` to run the check on all users that logged into Nextcloud at least once. You may use `--limit` and `--offset` to do so by batch. You can combine this with `--update` to update the information of seen users.

### ldap:check-group

Checks whether a group still exists in the LDAP directory. Use with `--update` to update the group membership cache on the Nextcloud side:

    sudo -E -u www-data php occ ldap:check-group --update mygroup

### ldap:create-empty-config

Creates an empty LDAP configuration. The first one you create has `configID` `s01`, and all subsequent configurations that you create are automatically assigned IDs:

    sudo -E -u www-data php occ ldap:create-empty-config
       Created new configuration with configID 's01'

Then you can list and view your configurations:

    sudo -E -u www-data php occ ldap:show-config

And view the configuration for a single configID:

    sudo -E -u www-data php occ ldap:show-config s01

### ldap:delete-config

Deletes an existing LDAP configuration:

    sudo -E -u www-data php occ ldap:delete  s01
    Deleted configuration with configID 's01'

### ldap:set-config

This command is for manipulating configurations, like this example that sets search attributes:

    sudo -E -u www-data php occ ldap:set-config s01 ldapAttributesForUserSearch
    "cn;givenname;sn;displayname;mail"

### ldap:test-config

Tests whether your configuration is correct and can bind to the server:

    sudo -E -u www-data php occ ldap:test-config s01
    The configuration is valid and the connection could be established!

### ldap:test-user-settings

Tests user-related LDAP settings:

    sudo -E -u www-data php occ ldap:test-user-settings "cn=philip j. fry,ou=people,dc=planetexpress,dc=com" --group "Everyone"

    User cn=philip j. fry,ou=people,dc=planetexpress,dc=com is mapped with account name fry.
    Known UUID is ce6cd914-71d5-103f-95a8-ad2dab17b2f9.
    Configuration prefix is s01

    Attributes set in configuration:
    - ldapExpertUsernameAttr: uid
    - ldapUuidUserAttribute: auto
    - ldapEmailAttribute: mail
    - ldapUserDisplayName: cn

    Attributes fetched from LDAP using filter (|(objectclass=inetOrgPerson)):
    - entryuuid: ["ce6cd914-71d5-103f-95a8-ad2dab17b2f9"]
    - uid: ["fry"]
    - mail: ["fry@planetexpress.com"]
    - cn: ["Philip J. Fry"]

    Detected UUID attribute: entryuuid

    UUID for cn=philip j. fry,ou=people,dc=planetexpress,dc=com: ce6cd914-71d5-103f-95a8-ad2dab17b2f9

    Group information:
    Configuration:
    - ldapGroupFilter: (|(objectclass=groupOfNames))
    - ldapGroupMemberAssocAttr: member

    Primary group:
    Group from gidNumber:
    All known groups: ["Ship crew", "Everyone"]
    MemberOf usage: off (0,1)

    Group Everyone:
    Group cn=everyone,ou=groups,dc=planetexpress,dc=com is mapped with name Everyone.
    Known UUID is ce8b61c2-71d5-103f-95af-ad2dab17b2f9.
    Members: ["bender", "fry", "leela"]

### ldap:show-remnants

Used to clean up the LDAP mappings table, and is documented in [../configuration_user/user_auth_ldap_cleanup](/link/1017).


# OCM commands

The `ocm` commands manage the signing keys that Nextcloud uses for Open Cloud Mesh (OCM) federation. Outbound OCM requests are signed with HTTP message signatures ([RFC 9421](https://www.rfc-editor.org/rfc/rfc9421)), and the matching public keys are published as a [JSON Web Key Set (JWKS)](https://www.rfc-editor.org/rfc/rfc7517) so that federated peers can verify them.

These commands are part of the server core and are always available. They are used to inspect and rotate the JWKS signing keys; you do not need them for normal operation, as a key is generated automatically on the first OCM request.

> **提示**
>
> For more on federation and OCM, see [Configuring Federation Sharing](/link/952).

    ocm
     ocm:keys:list       list JWKS-published signing keys
     ocm:keys:stage      generate a new JWKS key and advertise it via JWKS without using it for signing yet
     ocm:keys:activate   promote the staged JWKS key to active; the previous active key moves to retiring
     ocm:keys:retire     delete the retiring JWKS key; signatures that referenced its kid can no longer be verified

## Key slots

The signing keys live in three slots, all of which are published in the JWKS endpoint while they are populated:

- **active** — the key currently used to sign outbound OCM requests.
- **pending** — a newly staged key that is advertised in the JWKS but not yet used for signing. This gives federated peers time to pick it up before it becomes active.
- **retiring** — the previous active key, kept published so that signatures created with it can still be verified until it is removed.

## Listing keys

### ocm:keys:list

Show the current JWKS signing keys and the slot each one occupies:

    sudo -E -u www-data php occ ocm:keys:list
    +------+----------+--------------------------------+
    | Pool | Slot     | Key ID                         |
    +------+----------+--------------------------------+
    | 1    | active   | ecdsa-p256-sha256-...          |
    | 2    | pending  | ecdsa-p256-sha256-...          |
    +------+----------+--------------------------------+

If no keys exist yet, the command reports that one will be generated on the first OCM request. Use `--output=json` or `--output=json_pretty` for machine-readable output.

## Rotating keys

Key rotation is a three-step process: stage a new key, activate it, then retire the old one. Allow time between the steps so that federated peers can refresh their cached copy of your JWKS (the cache lifetime is one hour).

### ocm:keys:stage

Generate a new key into the **pending** slot. It is advertised in the JWKS but is not yet used for signing:

    sudo -E -u www-data php occ ocm:keys:stage
      Staged new JWKS key: ecdsa-p256-sha256-...
      Wait for federated peers to refresh their JWKS cache before activating.

An active key is required first; if none exists, one is generated automatically. The command fails if a pending key already exists — activate or retire it before staging another.

### ocm:keys:activate

Promote the staged (pending) key to **active**. The previous active key moves to the **retiring** slot, where it stays published in the JWKS so that in-flight signatures can still be verified:

    sudo -E -u www-data php occ ocm:keys:activate
      Staged key promoted to active.
      Run occ ocm:keys:retire once any in-flight signatures using the previous key have been verified.

The command fails if there is no pending key to activate, or if the retiring slot is still occupied — retire the previous key first.

### ocm:keys:retire

Delete the **retiring** key. Once removed, signatures that referenced its key ID can no longer be verified, so only run this after you are confident that no peer still needs it (for example, after at least one JWKS cache lifetime has passed since activation):

    sudo -E -u www-data php occ ocm:keys:retire
      Retiring key deleted.

The command fails if there is no retiring key to remove.


# User & group commands

## User commands

The `user` commands create and manage user accounts, reset passwords, manage authentication tokens, and report on user activity:

    user
     user:add                            adds a user
     user:add-app-password               (deprecated) alias for user:auth-tokens:add
     user:auth-tokens:add                add an app password for an account
     user:auth-tokens:delete             delete an authentication token
     user:auth-tokens:list               list authentication tokens for an account
     user:clear-avatar-cache             clear avatar cache
     user:delete                         deletes the specified user
     user:disable                        disables the specified user
     user:enable                         enables the specified user
     user:info                           show information about a user
     user:keys:verify                    verify the stored public key matches the stored private key
     user:lastseen                       show when a user was last logged in
     user:list                           list all registered users
     user:profile                        read and modify user profile data
     user:report                         show how many users have access
     user:resetpassword                  reset the password for a user
     user:setting                        read and modify user settings
     user:sync-account-data              sync user backend data to the accounts table
     user:welcome                        send the welcome email to a user

### user:add

Create a new user with a display name, login name, and optional group memberships:

    user:add [--password-from-env] [--generate-password] [--display-name[="..."]] [-g|--group[="..."]] [--email EMAIL] uid

The `display-name` corresponds to the **Full Name** on the Users page in your Nextcloud web interface, and the `uid` is their **Username** (login name). Any groups that do not exist are created automatically:

    sudo -E -u www-data php occ user:add --display-name="Layla Smith" \
      --group="users" --group="db-admins" layla
      Enter password:
      Confirm password:
      The user "layla" was created successfully
      Display name set to "Layla Smith"
      User "layla" added to group "users"
      User "layla" added to group "db-admins"

`--password-from-env` reads the password from the `OC_PASS` environment variable. This keeps the password out of the process list and allows scripting the creation of multiple users. Note that `sudo` strips environment variables by default; the `-E` flag preserves them, as shown in the example below:

    export OC_PASS=newpassword
    sudo -E -u www-data php occ user:add --password-from-env \
      --display-name="Layla Smith" --group="users" layla
    The user "layla" was created successfully
    Display name set to "Layla Smith"
    User "layla" added to group "users"

`--generate-password` sets a securely generated password that is never shown in the output. Combined with `--email`, this creates a user with a temporary password and sends a welcome email:

    sudo -E -u www-data php occ user:add layla --generate-password --email layla@example.tld
      The account "layla" was created successfully
      Welcome email sent to layla@example.tld

`--email` sets the user's email address and sends a welcome email if `newUser.sendEmail` is set to `yes` in the `core` app config, or if it is not set at all (`yes` is the default):

    sudo -E -u www-data php occ user:add layla --email layla@example.tld
      Enter password:
      Confirm password:
      The account "layla" was created successfully
      Welcome email sent to layla@example.tld

### user:resetpassword

Reset any user's password, including administrators (see [../configuration_user/reset_admin_password](/link/1011)):

    sudo -E -u www-data php occ user:resetpassword layla
      Enter a new password:
      Confirm the new password:
      Successfully reset password for layla

Clear a user's password with `--no-password`:

    sudo -E -u www-data php occ user:resetpassword --no-password layla
      Are you sure you want to clear the password for layla?
      Successfully reset password for layla

You may also use `--password-from-env` to reset passwords non-interactively:

    export OC_PASS=newpassword
    sudo -E -u www-data php occ user:resetpassword --password-from-env layla
      Successfully reset password for layla

### user:delete

Delete a user:

    sudo -E -u www-data php occ user:delete layla

### user:disable and user:enable

Disable a user. Their active sessions will be invalidated within 5 minutes. To invalidate sessions immediately, use `user:auth-tokens:delete` before or after disabling the account:

    sudo -E -u www-data php occ user:disable <username>

Re-enable a disabled user:

    sudo -E -u www-data php occ user:enable <username>

### user:lastseen

Show a specific user's most recent login:

    sudo -E -u www-data php occ user:lastseen layla
      layla's last login: 2024-03-20 17:18

Show all users' most recent logins:

    sudo -E -u www-data php occ user:lastseen --all
      albert's last login: 2024-03-18 10:30
      bob has never logged in.
      layla's last login: 2024-03-20 17:18
      stephanie's last login: 2024-01-11 13:26

### user:list

List all registered users. By default, output is limited to 500 users; use `--limit` and `--offset` to page through larger sets:

    sudo -E -u www-data php occ user:list
      - admin: admin
      - layla: Layla Smith
      - fred: Fred Jones

Use `--disabled` to list only disabled users, and `--info` to include additional backend details.

### user:info

Show account details for a user, including display name, email, groups, quota, and storage usage:

    sudo -E -u www-data php occ user:info layla
      - user_id: layla
      - display_name: Layla Smith
      - email: layla@example.tld
      - cloud_id: layla@cloud.example.tld
      - enabled: true
      - groups:
        - users
        - db-admins
      - quota: none
      - storage:
        - free: 162409623552
        - used: 1110
        - total: 162409624662
        - relative: 0
        - quota: -3
      - first_seen: 2024-03-01T08:44:46+00:00
      - last_seen: 2024-03-20T17:18:00+00:00
      - user_directory: /var/www/nextcloud/data/layla
      - backend: Database

### user:profile

Read user profile properties:

    sudo -E -u www-data php occ user:profile layla
      - displayname: Layla Smith
      - address: Berlin
      - email: layla@example.tld
      - profile_enabled: 1
      - pronouns: they/them

Get a single profile property:

    sudo -E -u www-data php occ user:profile layla address
      Berlin

Set a profile property:

    sudo -E -u www-data php occ user:profile layla address Stuttgart

Delete a profile property:

    sudo -E -u www-data php occ user:profile layla address --delete

### user:setting

Read user settings:

    sudo -E -u www-data php occ user:setting layla
      - core:
        - lang: en
      - login:
        - lastLogin: 1465910968
      - settings:
        - email: layla@example.tld

Filter by app:

    sudo -E -u www-data php occ user:setting layla core
      - core:
        - lang: en

Get a single setting:

    sudo -E -u www-data php occ user:setting layla core lang
    en

Set a setting:

    sudo -E -u www-data php occ user:setting layla settings email "new-layla@example.tld"

Delete a setting:

    sudo -E -u www-data php occ user:setting layla settings email --delete

### user:report

Show a count of all users, including users on external authentication backends such as LDAP:

    sudo -E -u www-data php occ user:report
    +------------------+----+
    | User Report      |    |
    +------------------+----+
    | Database         | 12 |
    | LDAP             | 86 |
    |                  |    |
    | total users      | 98 |
    |                  |    |
    | user directories | 2  |
    | active users     | 15 |
    | disabled users   | 0  |
    +------------------+----+

Active users are those who have logged in at least once. Users who have never logged in are not counted as active or disabled. Some backends do not support a user count and may show as zero.

### user:auth-tokens:list

List all active authentication tokens (sessions and app passwords) for a user:

    sudo -E -u www-data php occ user:auth-tokens:list layla
    +----+------------------+---------------------------+-----------+------------+
    | id | name             | lastActivity              | type      | scope      |
    +----+------------------+---------------------------+-----------+------------+
    | 42 | Firefox on Linux | 2024-03-20T17:18:00+00:00 | temporary | filesystem |
    | 47 | Backup script    | 2024-03-19T08:00:00+00:00 | permanent | filesystem |
    +----+------------------+---------------------------+-----------+------------+

Use `--output=json` or `--output=json_pretty` for machine-readable output.

### user:auth-tokens:add

Create an app password for a user. If no login password is provided, the generated token will have limited capabilities (operations that require the login password will fail):

    sudo -E -u www-data php occ user:auth-tokens:add --name="Backup script" layla
      Enter password:
      app password: kFrH9-TXk4s-gUoOQ-KOVH8

Use `--password-from-env` to read the login password from `NC_PASS` non-interactively:

    export NC_PASS=userpassword
    sudo -E -u www-data php occ user:auth-tokens:add --name="CI runner" \
      --password-from-env layla

### user:auth-tokens:delete

Delete a specific token by its ID (from `user:auth-tokens:list`):

    sudo -E -u www-data php occ user:auth-tokens:delete layla 47

Delete all tokens for a user that have not been used since a given date:

    sudo -E -u www-data php occ user:auth-tokens:delete layla \
      --last-used-before="2024-01-01"

### user:clear-avatar-cache

Clear the cached avatar images for all users. Useful after changing avatar storage settings or after migrating user data:

    sudo -E -u www-data php occ user:clear-avatar-cache

### user:keys:verify

Verify that the stored public key for a user matches their stored private key. Returns a confirmation or mismatch notice. Useful for diagnosing end-to-end encryption issues:

    sudo -E -u www-data php occ user:keys:verify layla
      Stored public key matches stored private key

### user:sync-account-data

Sync user data from the configured user backends (LDAP, SAML, etc.) to the Nextcloud accounts table. Useful after backend changes to ensure profile data, email addresses, and display names are up to date:

    sudo -E -u www-data php occ user:sync-account-data
      layla - updated

Use `--limit` and `--offset` to process users in batches.

### user:welcome

Send the welcome email to a user. The instance must have a working email configuration:

    sudo -E -u www-data php occ user:welcome layla

Add `--reset-password` to include a password reset link in the email:

    sudo -E -u www-data php occ user:welcome --reset-password layla

## Group commands

The `group` commands create and manage groups and their memberships:

    group
     group:add                           add a group
     group:adduser                       add a user to a group
     group:delete                        remove a group
     group:info                          show information about a group
     group:list                          list configured groups
     group:removeuser                    remove a user from a group

### group:add

Create a new group:

    sudo -E -u www-data php occ group:add milliways

### group:adduser and group:removeuser

Add one or more existing users to the specified group with the `group:adduser` command. The syntax is:

    group:adduser <gid> <uid1> [uid2 ... uidN]

This example adds the users "denis", "dora" and "daisy" to the existing group "milliways":

    sudo -E -u www-data php occ group:adduser milliways denis dora daisy

You can remove one or more users from the group with the `group:removeuser` command. This example removes the existing users "denis", "dora" and "daisy" from the existing group "milliways":

    sudo -E -u www-data php occ group:removeuser milliways denis dora daisy

### group:delete

Remove a group. This does not delete the users in the group. The `admin` group cannot be removed:

    sudo -E -u www-data php occ group:delete milliways

### group:list

List configured groups. Optionally filter by a search string:

    sudo -E -u www-data php occ group:list
      - admin:
        - admin
      - milliways:
        - layla
      - users:
        - layla

    sudo -E -u www-data php occ group:list milli
      - milliways:
        - layla

Use `--limit` and `--offset` to page through large numbers of groups. Use `--info` to include the backend for each group. Use `--output=json` or `--output=json_pretty` for machine-readable output.

### group:info

Show details about a group, including its members and backend:

    sudo -E -u www-data php occ group:info admin
      - groupID: admin
      - displayName: admin
      - backends:
        - Database

Use `--output=json_pretty` for machine-readable output.

## Two-factor authentication

The `twofactorauth` commands manage two-factor authentication (2FA) enforcement and provider state:

    twofactorauth
     twofactorauth:cleanup               clean up provider associations for a removed provider
     twofactorauth:disable               disable 2FA for a user (provider-specific)
     twofactorauth:enable                enable 2FA for a user (provider-specific)
     twofactorauth:enforce               enforce or disable mandatory 2FA globally or per group
     twofactorauth:state                 show the 2FA state for a user

### twofactorauth:disable and twofactorauth:enable

If a user loses access to their second factor (for example, a lost phone), an admin can disable 2FA for that user for a specific provider:

    sudo -E -u www-data php occ twofactorauth:disable <uid> <provider_id>

Re-enable 2FA for the user:

    sudo -E -u www-data php occ twofactorauth:enable <uid> <provider_id>

> **提示**
>
> Not all 2FA providers support per-user enable/disable via occ.

### twofactorauth:enforce

Enforce 2FA for all users:

    sudo -E -u www-data php occ twofactorauth:enforce --on
      Two-factor authentication is enforced for all users

Enforce 2FA only for specific groups, optionally excluding others:

    sudo -E -u www-data php occ twofactorauth:enforce --on \
      --group=admin --group=finance --exclude=service-accounts
      Two-factor authentication is enforced for members of the group(s) admin, finance

Disable enforcement:

    sudo -E -u www-data php occ twofactorauth:enforce --off
      Two-factor authentication is not enforced

### twofactorauth:state

Show whether 2FA is enabled, enforced, and which providers are active for a user:

    sudo -E -u www-data php occ twofactorauth:state layla
      Two-factor authentication is not enabled for user layla

      Disabled providers:
      - backup_codes
      - totp

### twofactorauth:cleanup

Remove stored 2FA provider associations for a provider that has been uninstalled. This cleans up stale data after removing a 2FA app:

    sudo -E -u www-data php occ twofactorauth:cleanup <provider_id>

## System Tags

System tags are admin-managed labels that can be assigned to files for use in workflows and automated actions.

Tags have three access levels:

| Level      | Visible¹ | Assignable² |
|------------|----------|-------------|
| public     | Yes      | Yes         |
| restricted | Yes      | No          |
| invisible  | No       | No          |

¹ User can see the tag\
² User can assign the tag to a file

See [../file_workflows/automated_tagging](/link/978) for typical use cases for restricted and invisible tags, such as retention and access control.

### tag:list

List all system tags:

    sudo -E -u www-data php occ tag:list
      - 1:
        - name: confidential
        - access: restricted
      - 2:
        - name: needs-review
        - access: public

### tag:add

Create a new system tag:

    sudo -E -u www-data php occ tag:add confidential restricted
      - id: 1
      - name: confidential
      - access: restricted

### tag:edit

Rename a tag or change its access level. Use the tag ID from `tag:list`:

    sudo -E -u www-data php occ tag:edit --name "reviewed" --color="" 2
      Tag updated ("reviewed", true, true, "")

`--name` and `--access` are optional. `--color=""` must be passed explicitly due to a known issue with the command.

### tag:delete

Delete a tag by its ID:

    sudo -E -u www-data php occ tag:delete 1
      The specified tag was deleted

### Assigning tags to files

Add one or more tags to a file or directory (specified by file ID or path). The `access` argument identifies which tag to apply — because two tags can share the same name but have different access levels, both name and access level are required to uniquely identify a tag. If no matching tag exists, it is created automatically:

    sudo -E -u www-data php occ tag:files:add /layla/files/report.pdf confidential restricted
      restricted tag named confidential added.

Multiple tags can be specified as a comma-separated list. All tags in a single call must share the same access level.

Remove specific tags from a file:

    sudo -E -u www-data php occ tag:files:delete /layla/files/report.pdf confidential restricted

Remove all tags from a file:

    sudo -E -u www-data php occ tag:files:delete-all /layla/files/report.pdf


# System & maintenance commands

The `occ` commands in this section cover server administration, background job management, and operational tasks. They let you configure logging and theming, manage background jobs and AI task processing, administer OAuth2 clients, delegation rules and workflows, check server status, and perform installation and upgrade procedures from the command line.

## Admin delegation

The `admin-delegation` commands allow granting non-admin groups access to specific admin settings panels, without giving them full administrator privileges:

    admin-delegation
     admin-delegation:add     add setting delegation to a group
     admin-delegation:remove  remove settings delegation from a group
     admin-delegation:show    show delegated settings

### admin-delegation:add

Delegate an admin settings class to a group:

    sudo -E -u www-data php occ admin-delegation:add \
      'OCA\Settings\Settings\Admin\Sharing' milliways

The `settingClass` argument must be the fully qualified PHP class name of a settings class that implements `IDelegatedSettings`. Common examples:

- `OCA\Settings\Settings\Admin\Sharing` — sharing administration
- `OCA\Settings\Settings\Admin\Users` — user management
- `OCA\Settings\Settings\Admin\Mail` — email configuration
- `OCA\Theming\Settings\Admin` — theming settings

### admin-delegation:remove

Remove a settings delegation from a group:

    sudo -E -u www-data php occ admin-delegation:remove \
      'OCA\Settings\Settings\Admin\Sharing' milliways

### admin-delegation:show

Show all currently configured settings delegations:

    sudo -E -u www-data php occ admin-delegation:show

Use `--output=json_pretty` for machine-readable output.

## Background jobs

The `background-job` commands let you inspect and execute individual background jobs. The separate `background:cron`, `background:ajax`, and `background:webcron` commands configure how the background job scheduler is triggered:

    background
     background:ajax     use ajax to run background jobs
     background:cron     use cron to run background jobs
     background:webcron  use webcron to run background jobs
    background-job
     background-job:delete   Remove a background job from database
     background-job:execute  Execute a single background job manually
     background-job:history  Show past jobs
     background-job:list     List background jobs
     background-job:running  Show currently running jobs
     background-job:worker   Run a background job worker

### background:cron

Set the background job execution mode to cron. Nextcloud recommends the system cron mode for production instances:

    sudo -E -u www-data php occ background:cron
      Set mode for background jobs to 'cron'

Use `background:ajax` to switch to the in-browser AJAX scheduler or `background:webcron` for an external webcron service instead.

See [../configuration_server/background_jobs_configuration](/link/924) for a full guide to configuring the background job scheduler.

### background-job:delete

Remove a background job from the database. The command shows the job details and asks for confirmation:

    sudo -E -u www-data php occ background-job:delete 42
      Job class: OCA\Files\BackgroundJob\ScanFiles
      Arguments: []

      Do you really want to delete this background job? It could create some misbehaviours in Nextcloud. (y/N)

> **注意**
>
> Deleting a background job can cause Nextcloud features to stop working correctly. Only delete jobs that you know are safe to remove, such as duplicate or orphaned entries.

### background-job:execute

Execute a single background job by its database ID:

    sudo -E -u www-data php occ background-job:execute 42

The command shows the job's class, type, last run time, and next scheduled execution before running it. If the job was recently run and is not yet due, it may be skipped; use `--force-execute` to run it regardless:

    sudo -E -u www-data php occ background-job:execute --force-execute 42

### background-job:history

Show job history with their duration and peak memory usage:

    sudo -E -u www-data php occ background-job:history -l 5
    +-------------------+-----------+-------------------------------------------+---------------------+-----------+---------+-----------+--------------+
    | Run ID            | Status    | Class                                     | Started at          | Server ID | PID     | Duration  | Memory usage |
    +-------------------+-----------+-------------------------------------------+---------------------+-----------+---------+-----------+--------------+
    | 98109593040965632 | Succeeded | OC\Command\CommandJob                     | 2026-06-22 09:15:19 | 30        | 3847229 | 284 ms    | 251.6 MB     |
    | 98109592927719424 | Succeeded | OC\FilesMetadata\Job\UpdateSingleMetadata | 2026-06-22 09:15:19 | 30        | 3847229 | 16 ms     | 222 MB       |
    | 98109592852221952 | Succeeded | OC\FilesMetadata\Job\UpdateSingleMetadata | 2026-06-22 09:15:19 | 30        | 3847229 | 8 ms      | 221.4 MB     |
    | 98109588267847680 | Succeeded | OC\Command\CommandJob                     | 2026-06-22 09:15:18 | 30        | 3847229 | 909 ms    | 293 MB       |
    | 97985889682313216 | Crashed   | OCA\Text\Cron\Cleanup                     | 2026-06-22 01:15:17 | 30        | 3733554 | 594627 ms | 0 B          |
    +-------------------+-----------+-------------------------------------------+---------------------+-----------+---------+-----------+--------------+

Use `-l`/`--limit` to control how many jobs are shown (default: 200), one or multiple `-c`/`--class` to filter by job class, and one or multiple `-s`/`--status` to filter by status (0: running, 1: succeeded, 2: failed, 3: crashed).

### background-job:list

List all background jobs registered in the database:

    sudo -E -u www-data php occ background-job:list
    +----+------------------------------------------------------+---------------------------+------------+
    | id | class                                                | last_run                  | argument   |
    +----+------------------------------------------------------+---------------------------+------------+
    | 1  | OCA\Files\BackgroundJob\ScanFiles                    | 2025-06-23T10:00:00+00:00 | []         |
    | 2  | OCA\Activity\BackgroundJob\DigestMail                | 2025-06-23T08:00:00+00:00 | []         |
    | 3  | OC\Share20\SharesReminderJob                         | 2025-06-23T07:00:00+00:00 | []         |
    +----+------------------------------------------------------+---------------------------+------------+

Use `-c` / `--class` to filter by job class, `-l` / `--limit` to control how many jobs are shown (default: 500), and `-o` / `--offset` to page through results.

### background-job:running

List all currently running jobs:

    sudo -E -u www-data php occ background-job:running
    +-------------------+-----------------------+---------------------+-----------+---------+---------------+
    | Run ID            | Class                 | Started at          | Server ID | PID     | Running since |
    +-------------------+-----------------------+---------------------+-----------+---------+---------------+
    | 98108257692012544 | OC\Command\CommandJob | 2026-06-22 09:10:08 | 30        | 3845056 | 1 seconds     |
    +-------------------+-----------------------+---------------------+-----------+---------+---------------+

Use `-l` / `--limit` to limit the number of job shown (default: 200).

### background-job:worker

Run a continuous background job worker. This is an alternative to system cron for environments where you want to run background jobs from a persistent process rather than a periodic cron invocation:

    sudo -E -u www-data php occ background-job:worker

By default the worker runs indefinitely, polling for new jobs every second.

Use `--once` to process at most one job then exit (equivalent to a single cron run):

    sudo -E -u www-data php occ background-job:worker --once

Use `--stop_after` to set a maximum runtime before the worker exits cleanly (the currently running job is allowed to finish). Accepts seconds, or values like `30s`, `10m`, `2h`:

    sudo -E -u www-data php occ background-job:worker --stop_after 1h

Use `--interval` to set the poll interval in seconds (default: 1). Set to `0` to process jobs once and exit if none are found:

    sudo -E -u www-data php occ background-job:worker --interval 5

Pass one or more job class names to process only jobs of those types:

    sudo -E -u www-data php occ background-job:worker \
      'OCA\Files\BackgroundJob\ScanFiles'

## Broadcast

Send a test Server-Sent Events (SSE) broadcast to verify that real-time push notifications are working:

    sudo -E -u www-data php occ broadcast:test layla

Pass a custom event name as the second argument (default: `test`):

    sudo -E -u www-data php occ broadcast:test layla my-event

## Info

The `info` commands display detailed information about files and storages. They are useful for debugging file access problems, investigating storage layout, and identifying space usage:

    info
     info:file        get information for a file
     info:file:space  summarize space usage of a folder
     info:storage     get information for a single storage
     info:storages    list storages ordered by file count

### info:file

Show detailed information for a file or folder identified by file ID or path:

    sudo -E -u www-data php occ info:file /layla/files/Documents/report.pdf
      FileId: 12345
      MimeType: application/pdf
      Modified: 2025-06-01T14:30:00+00:00
      Encrypted: false
      Size: 204800
      ETag: abc123
      Permissions: 27
      Users with access: layla

Use `-c` / `--children` to list the immediate contents of a folder. Use `--storage-tree` to display the storage and cache wrapping tree.

### info:file:space

Show how much space a folder uses, with a ranked breakdown of the largest items:

    sudo -E -u www-data php occ info:file:space /layla/files/Videos
      Total: 14.7 GB
      +------------------+--------+
      | Path             | Size   |
      +------------------+--------+
      | lecture-2025.mp4 | 8.2 GB |
      | demo-video.mp4   | 4.1 GB |
      +------------------+--------+

Use `-c` / `--count` to change the number of items shown (default: 25), or `-a` / `--all` to show all items.

### info:storage

Show information for a single storage by its numeric storage ID:

    sudo -E -u www-data php occ info:storage 5

### info:storages

List all storages ordered by the number of files they contain:

    sudo -E -u www-data php occ info:storages

Use `-c` / `--count` to limit the number of storages shown (default: 25), or `-a` / `--all` to list all storages.

## Logging commands

These commands view and configure your Nextcloud logging preferences:

    log
     log:file    manipulate Nextcloud logging backend
     log:manage  manage logging configuration
     log:tail    tail the Nextcloud logfile [requires app "Log Reader" to be enabled]
     log:watch   watch the Nextcloud logfile live [requires app "Log Reader" to be enabled]

### log:file

Show the current logging status:

    sudo -E -u www-data php occ log:file
      Log backend Nextcloud: enabled
      Log file: /opt/nextcloud/data/nextcloud.log
      Rotate at: disabled

Use `--enable` to turn on the Nextcloud log backend, `--file` to set a different log file path, and `--rotate-size` to rotate the log at a given file size in bytes (`0` disables rotation).

### log:manage

Set the logging backend, log level, and timezone. The defaults are `file`, `warning`, and `UTC`:

    sudo -E -u www-data php occ log:manage --backend file --level warning --timezone UTC
      Log backend: file
      Log level: Warning (2)
      Log timezone: UTC

Options:

- `--backend` — one of: `file`, `syslog`, `errorlog`, `systemd`
- `--level` — one of: `debug`, `info`, `warning`, `error`, `fatal`
- `--timezone` — a PHP timezone name; see <https://www.php.net/manual/en/timezones.php>

## Maintenance commands

Use these commands when you upgrade Nextcloud, perform backups, or carry out other tasks that require locking users out temporarily:

    maintenance
     maintenance:data-fingerprint    update the systems data-fingerprint after a backup is restored
     maintenance:mimetype:update-db  update database mimetypes and update filecache
     maintenance:mimetype:update-js  update mimetypelist.js
     maintenance:mode                set maintenance mode
     maintenance:repair              repair this installation
     maintenance:repair-share-owner  fix some shares owner if it fell out of sync
     maintenance:theme:update        apply custom theme changes
     maintenance:update:htaccess     update the .htaccess file

### maintenance:data-fingerprint

After restoring a backup of your data directory or the database, run this command once. It updates the ETag for all files, allowing sync clients to detect that files were modified:

    sudo -E -u www-data php occ maintenance:data-fingerprint

### maintenance:mimetype:update-db and maintenance:mimetype:update-js

Update the Nextcloud database and file cache with changed mimetypes from `config/mimetypemapping.json`. Run after modifying that file. Pass `--repair-filecache` to apply the change to existing files:

    sudo -E -u www-data php occ maintenance:mimetype:update-db --repair-filecache

`maintenance:mimetype:update-js` regenerates the client-side mimetype list:

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

### maintenance:mode

Lock the sessions of all logged-in users, including administrators, and display a status screen warning that the server is in maintenance mode. Users who are not already logged in cannot log in until maintenance mode is turned off. When the server comes out of maintenance mode, logged-in users must refresh their browser to continue working:

    sudo -E -u www-data php occ maintenance:mode --on
      Maintenance mode enabled

    sudo -E -u www-data php occ maintenance:mode --off
      Maintenance mode disabled

### maintenance:repair

Runs automatically during upgrades to clean up the database. You can also run it manually if needed:

    sudo -E -u www-data php occ maintenance:repair

### maintenance:repair-share-owner

Fix share owner records that have fallen out of sync with the actual file ownership:

    sudo -E -u www-data php occ maintenance:repair-share-owner

### maintenance:theme:update

Run when icons in a custom theme are not updating correctly. This rebuilds the mimetype list and clears the image cache:

    sudo -E -u www-data php occ maintenance:theme:update

### maintenance:update:htaccess

Regenerate the `.htaccess` file from the current configuration. Run this after changing URL rewriting settings or after an upgrade if the file appears outdated:

    sudo -E -u www-data php occ maintenance:update:htaccess

## OAuth2

> **提示**
>
> This command is only available when `'oauth2.enable_oc_clients' => true` is set in `config/config.php`. It is intended for ownCloud-to-Nextcloud migrations only.

Import an OAuth2 client record from an ownCloud database during a migration. The `client-id` and `client-secret` arguments come directly from the `oc_oauth2_clients` table in the ownCloud database:

    sudo -E -u www-data php occ oauth2:import-legacy-oc-client \
      <client-id> <client-secret>

## Security

Use these commands to manage server-wide security parameters, including [Brute force protection](/link/925) and trusted SSL certificates. Trusted certificates are useful when creating federation connections with servers that use self-signed certificates:

    security
     security:bruteforce:attempts  show bruteforce attempts status for a given IP address
     security:bruteforce:reset     reset bruteforce attempts for a given IP address
     security:certificates         list trusted certificates
     security:certificates:export  export the certificate bundle
     security:certificates:import  import trusted certificate
     security:certificates:remove  remove trusted certificate

### security:bruteforce:attempts

Show the current bruteforce throttle status for an IP address, including the number of recorded attempts and the current delay being applied. Optionally filter by action name:

    sudo -E -u www-data php occ security:bruteforce:attempts 192.168.1.100
    sudo -E -u www-data php occ security:bruteforce:attempts 192.168.1.100 login

Use `--output=json_pretty` for machine-readable output.

### security:bruteforce:reset

Clear all recorded bruteforce attempts for an IP address, removing any login delay immediately:

    sudo -E -u www-data php occ security:bruteforce:reset 192.168.1.100

### security:certificates

List all trusted certificates installed on the server:

    sudo -E -u www-data php occ security:certificates
    +---------------------+-------------+-------------------+-------------+-----------+
    | File Name           | Common Name | Organization      | Valid Until | Issued By |
    +---------------------+-------------+-------------------+-------------+-----------+
    | myserver.crt        | myserver    | My Org            | 2026-01-01  | My CA     |
    +---------------------+-------------+-------------------+-------------+-----------+

Use `--output=json_pretty` for machine-readable output.

### security:certificates:export

Export the full certificate bundle to stdout. Useful for backup or inspection:

    sudo -E -u www-data php occ security:certificates:export

### security:certificates:import

Install a trusted certificate from a file. The certificate name is derived from the filename:

    sudo -E -u www-data php occ security:certificates:import /path/to/certificate.crt

### security:certificates:remove

Remove a trusted certificate by its file name (as shown in `security:certificates`):

    sudo -E -u www-data php occ security:certificates:remove my-certificate

## Setup checks

Run the setup checks from the command line to verify your installation configuration:

    sudo -E -u www-data php occ setupchecks

Example output:

    dav:
      ✓ DAV system address book: No outstanding DAV system address book sync.
    network:
      ✓ WebDAV endpoint: Your web server is properly set up to allow file synchronization over WebDAV.
      ✓ Data directory protected
      ✓ Internet connectivity
      ...

Use `--output=json_pretty` for machine-readable output suitable for automated monitoring.

Use `--class=CLASS_NAME`" to run only the check for the setup check with the given class name.

Use `--category=CATEGORY` to run only the checks for the given category, e.g. `network` or `system`.

## Share operations

Available `occ` commands for the `share` namespace:

    share
     share:list  list available shares

### share:list

List all shares on the system:

    sudo -E -u www-data php occ share:list

Filter by owner, recipient, or the user who created the share:

    sudo -E -u www-data php occ share:list --owner layla
    sudo -E -u www-data php occ share:list --recipient fred
    sudo -E -u www-data php occ share:list --by layla

Filter by a specific file path:

    sudo -E -u www-data php occ share:list --file "/layla/files/Documents/report.pdf"

Filter by a folder; use `--recursive` to include shares nested anywhere inside it:

    sudo -E -u www-data php occ share:list --parent "/layla/files/Projects" --recursive

Filter by share type (one of `user`, `group`, `link`, `email`, `remote`, `room`, `deck`) or by share status:

    sudo -E -u www-data php occ share:list --type link
    sudo -E -u www-data php occ share:list --status 0

## Snowflake IDs

Nextcloud uses Snowflake IDs for unique identifiers in several subsystems. Decode a Snowflake ID to inspect its embedded timestamp and metadata:

    sudo -E -u www-data php occ snowflake:decode 6768789079123765868

Example output:

    +--------------------+-------------------------+
    | Snowflake ID       | 6768789079123765868     |
    | Seconds            | 1575981518              |
    | Milliseconds       | 50                      |
    | Created from CLI   | no                      |
    | Server ID          | 441                     |
    | Sequence ID        | 2668                    |
    | Creation timestamp | 1575981518.050          |
    | Creation date      | 2019-12-10 11:18:38.050 |
    +--------------------+-------------------------+

## Status

Use the `status` command to retrieve information about the current installation:

    sudo -E -u www-data php occ status
      - installed: true
      - version: 30.0.0.0
      - versionstring: 30.0.0
      - edition:
      - maintenance: false
      - needsDbUpgrade: false
      - productname: Nextcloud
      - extendedSupport: false

Use `--output=json_pretty` for machine-readable output:

    sudo -E -u www-data php occ status --output=json_pretty
    {
        "installed": true,
        "version": "30.0.0.0",
        "versionstring": "30.0.0",
        "edition": "",
        "maintenance": false,
        "needsDbUpgrade": false,
        "productname": "Nextcloud",
        "extendedSupport": false
    }

### Status return code

Use the `-e` flag to get a machine-readable exit code reflecting the installation state. There is no output by default, making it suitable for scripts, monitoring checks, and systemd units:

    sudo -E -u www-data php occ status -e
    echo $?
    0
    sudo -E -u www-data php occ maintenance:mode --on
    Maintenance mode enabled
    sudo -E -u www-data php occ status -e
    echo $?
    1
    sudo -E -u www-data php occ maintenance:mode --off
    Maintenance mode disabled
    sudo -E -u www-data php occ status -e
    echo $?
    0

| Return code | Description |
|----|----|
| 0 | normal operation |
| 1 | maintenance mode is enabled; the instance is currently unavailable to users |
| 2 | `occ upgrade` is required |

## Task processing

The `taskprocessing` commands manage AI and background task processing jobs. Task processing provides infrastructure for AI features such as text generation, image classification, and speech-to-text:

    taskprocessing
     taskprocessing:task-type:set-enabled enable or disable a task type
     taskprocessing:task:cleanup          cleanup old tasks
     taskprocessing:task:get              display all information for a specific task
     taskprocessing:task:list             list tasks
     taskprocessing:task:stats            get statistics for tasks
     taskprocessing:worker                run a dedicated worker for synchronous TaskProcessing providers

### taskprocessing:task-type:set-enabled

Enable or disable a task type:

    sudo -E -u www-data php occ taskprocessing:task-type:set-enabled core:text2text 1
    sudo -E -u www-data php occ taskprocessing:task-type:set-enabled core:text2text 0

### taskprocessing:task:cleanup

Delete old task records and their associated output files. By default, tasks older than four months are removed:

    sudo -E -u www-data php occ taskprocessing:task:cleanup

Pass a maximum age in seconds to override the default:

    sudo -E -u www-data php occ taskprocessing:task:cleanup 2592000

### taskprocessing:task:get

Display all information for a specific task by its numeric ID:

    sudo -E -u www-data php occ taskprocessing:task:get 42

### taskprocessing:task:list

List task processing tasks:

    sudo -E -u www-data php occ taskprocessing:task:list

Filter by user, type, app, or custom ID:

    sudo -E -u www-data php occ taskprocessing:task:list --userIdFilter layla
    sudo -E -u www-data php occ taskprocessing:task:list --type core:text2text

Filter by status (0=UNKNOWN, 1=SCHEDULED, 2=RUNNING, 3=SUCCESSFUL, 4=FAILED, 5=CANCELLED):

    sudo -E -u www-data php occ taskprocessing:task:list --status 4

Other available filters: `--appId`, `--customId`, `--scheduledAfter`, `--endedBefore`.

### taskprocessing:task:stats

Show statistics for tasks (max/average running time, queuing time, and input/output sizes). Accepts the same filter options as `taskprocessing:task:list`:

    sudo -E -u www-data php occ taskprocessing:task:stats

### taskprocessing:worker

Run a dedicated worker that processes tasks from synchronous TaskProcessing providers. Use this when you want to offload AI task execution to a separate process:

    sudo -E -u www-data php occ taskprocessing:worker

Use `--once` to process at most one task then exit. Use `--timeout` to set a maximum runtime in seconds (default: `0` = run indefinitely). Use `--taskTypes` (repeatable) to restrict the worker to specific task type IDs:

    sudo -E -u www-data php occ taskprocessing:worker \
      --taskTypes core:text2text --once

## Theming

The Theming app (`theming`) is always enabled. The `theming:config` command lets you view and update theming settings without logging into the web interface:

    theming
     theming:config  set theming app config values

### theming:config

With no arguments, show all current theming values:

    sudo -E -u www-data php occ theming:config
      Current theming config:
      name: Nextcloud
      url: https://nextcloud.com
      slogan: a safe home for all your data
      ...

Show the current value of a single key:

    sudo -E -u www-data php occ theming:config name

Set a value:

    sudo -E -u www-data php occ theming:config name "Acme Cloud"
    sudo -E -u www-data php occ theming:config url "https://acme.example.com"
    sudo -E -u www-data php occ theming:config slogan "Secure file sync for Acme"
    sudo -E -u www-data php occ theming:config primary_color "#0082c9"
    sudo -E -u www-data php occ theming:config background_color "#00679e"
    sudo -E -u www-data php occ theming:config disable-user-theming true

To set an image, pass the path to the image file as the value:

    sudo -E -u www-data php occ theming:config logo /path/to/logo.png
    sudo -E -u www-data php occ theming:config favicon /path/to/favicon.ico
    sudo -E -u www-data php occ theming:config background /path/to/background.jpg

Reset a key to its default:

    sudo -E -u www-data php occ theming:config --reset name

Supported text keys: `name`, `url`, `imprintUrl`, `privacyUrl`, `slogan`, `primary_color`, `background_color`, `disable-user-theming`.

Supported image keys: `background`, `logo`, `logoheader`, `favicon`.

## Webhook listeners

> **提示**
>
> The Webhook listeners app (`webhook_listeners`) is shipped with Nextcloud but not enabled by default. Enable it in the Apps menu before using these commands.

List all webhook listener configurations registered on the server. Each entry shows the listener ID, the user or app that registered it, the HTTP method and target URI, the Nextcloud event it listens for, any event filter, and the configured authentication method (`none` or `header`):

    sudo -E -u www-data php occ webhook_listeners:list

Use `--output=json_pretty` for machine-readable output, which also includes the full header and authentication data fields:

    sudo -E -u www-data php occ webhook_listeners:list --output=json_pretty

Webhook listeners are configured through the Admin settings UI or the REST API. This command is read-only — it provides an audit view of what listeners are active without needing to access the web interface.

## Workflows

The Workflow engine (`workflowengine`) is always enabled:

    workflows
     workflows:list  list configured workflows

### workflows:list

List configured workflow rules. Use the optional `scope` argument to filter by scope; `admin` (default) or `user`:

    sudo -E -u www-data php occ workflows:list
    sudo -E -u www-data php occ workflows:list user
    sudo -E -u www-data php occ workflows:list user layla

The output is a JSON representation of the configured workflow operations.

## Command line installation

These commands are only available before Nextcloud has been installed, after you have unpacked the archive and copied Nextcloud into the appropriate directories.

Display the available installation options:

```console
$ sudo -E -u www-data php /var/www/nextcloud/occ maintenance:install --help
Nextcloud is not installed - only a limited number of commands are available

Usage:
  maintenance:install [options]

Options:
      --database[=DATABASE]                  Supported database type [default: "sqlite"]
      --database-name[=DATABASE-NAME]        Name of the database
      --database-host[=DATABASE-HOST]        Hostname of the database [default: "localhost"]
      --database-port[=DATABASE-PORT]        Port the database is listening on
      --database-user[=DATABASE-USER]        Login for database connection
      --database-pass[=DATABASE-PASS]        Password of the database login
      --database-table-space[=DATABASE-TABLE-SPACE]
                                                Table space of the database (``oci`` only)
      --database-ssl-mode[=DATABASE-SSL-MODE]
                                                Encryption mode for the database connection,
                                                e.g. "require" or "verify-full" (``pgsql`` only)
      --database-ssl-ca[=DATABASE-SSL-CA]    Path to the CA certificate the database server
                                                is verified against (``mysql`` and ``pgsql`` only)
      --database-ssl-cert[=DATABASE-SSL-CERT]
                                                Path to the client certificate used to
                                                authenticate against the database
                                                (``mysql`` and ``pgsql`` only)
      --database-ssl-key[=DATABASE-SSL-KEY]  Path to the private key of the client certificate
                                                (``mysql`` and ``pgsql`` only)
      --database-ssl-crl[=DATABASE-SSL-CRL]  Path to the certificate revocation list
                                                (``pgsql`` only)
      --database-ssl-no-verify               Do not verify that the database server certificate
                                                matches the hostname used to connect
                                                (``mysql`` only)
      --disable-admin-user                   Disable the creation of an administrator login
      --admin-user[=ADMIN-USER]              Login for initial administrator account [default: "admin"]
      --admin-pass[=ADMIN-PASS]              Password for initial administrator login
      --admin-email[=ADMIN-EMAIL]            E-Mail to associate with the initial administrator login
      --data-dir[=DATA-DIR]                  Path to data directory
      --password-salt[=PASSWORD-SALT]        Password salt; generated if not provided (ADVANCED)
      --server-secret[=SERVER-SECRET]        Server secret; generated if not provided (ADVANCED)
```

This example installs Nextcloud with a MySQL database. `occ` prompts for the database and administrator passwords:

```console
$ sudo -E -u www-data php /var/www/nextcloud/occ maintenance:install \
    --database mysql \
    --database-name nextcloud \
    --database-host 127.0.0.1 \
    --database-user nextcloud \
    --admin-user admin
What is the password to access the database with user <nextcloud>?
What is the password you like to use for the admin account <admin>?
Nextcloud was successfully installed
```

Supported databases:

- `sqlite` — SQLite (not recommended for production usage)
- `mysql` — MySQL or MariaDB
- `pgsql` — PostgreSQL
- `oci` — Oracle; contact [Nextcloud GmbH](https://nextcloud.com/enterprise/) for enterprise support

> *New in version 35:* The `--database-ssl-*` options set up an SSL/TLS encrypted connection to the database, see [Encrypted database connection](/link/899).

## Command line upgrade

These commands are available after downloading an upgraded package or tarball, and before completing the upgrade.

> **说明**
>
> `occ upgrade` only runs the **migration phase**: database schema updates and app upgrades. It does **not** download or replace Nextcloud's code files.
>
> Before running `occ upgrade` you must first replace the code using one of:
>
> - The built-in updater: `sudo -E -u www-data php /var/www/nextcloud/updater/updater.phar`
> - A manually extracted tarball (see [../maintenance/manual_upgrade](/link/1066))
>
> If `occ upgrade` reports *"Nextcloud is up to date"* when you expect an upgrade to run, the code files have not been replaced yet — run the updater or extract the new tarball first.
>
> See [../maintenance/upgrade](/link/1064) for the full upgrade process.

When performing an upgrade, use `occ upgrade` instead of the web-based upgrader to avoid PHP timeout limits (the web interface enforces a 3600-second limit). On large installations this may not be sufficient, leaving the system in an inconsistent state.

After completing all preliminary steps (see [../maintenance/upgrade](/link/1064)), run the upgrade:

    sudo -E -u www-data php occ upgrade
      Nextcloud or one of the apps require upgrade - only a limited number of
      commands are available
      Turned on maintenance mode
      Checked database schema update
      Checked database schema update for apps
      Updated database
      Updating <gallery> ...
      Updated <gallery> to 0.6.1
      Updating <activity> ...
      Updated <activity> to 2.1.0
      Update successful
      Turned off maintenance mode

Use `-v` to display timestamps on each step:

    sudo -E -u www-data php occ upgrade -v
      2025-06-23T09:06:15+0000 Turned on maintenance mode
      2025-06-23T09:06:15+0000 Checked database schema update
      2025-06-23T09:06:15+0000 Checked database schema update for apps
      2025-06-23T09:06:15+0000 Updated database
      2025-06-23T09:06:15+0000 Updated <files_sharing> to 0.6.6
      2025-06-23T09:06:15+0000 Update successful
      2025-06-23T09:06:15+0000 Turned off maintenance mode

If an error occurs, the exception is logged in the Nextcloud log file:

    Turned on maintenance mode
    Checked database schema update
    Checked database schema update for apps
    Updated database
    Updating <files_sharing> ...
    Exception
    ServerNotAvailableException: LDAP server is not available
    Update failed
    Turned off maintenance mode

## Antivirus

> **提示**
>
> These commands require the [files_antivirus](https://apps.nextcloud.com/apps/files_antivirus) app to be installed and enabled.

    files_antivirus
     files_antivirus:background-scan  run the background scan
     files_antivirus:mark             mark a file as scanned or unscanned
     files_antivirus:scan             scan a file
     files_antivirus:status           show antivirus scanner status

### files_antivirus:background-scan

Trigger the background antivirus scan manually. By default all pending files are processed. Use `--max` to limit the number of files scanned in a single run:

    sudo -E -u www-data php occ files_antivirus:background-scan
    sudo -E -u www-data php occ files_antivirus:background-scan --max 500

### files_antivirus:mark

Mark a file as scanned or unscanned. The `file` argument is the path to the file and `mode` is either `scanned` or `unscanned`:

    sudo -E -u www-data php occ files_antivirus:mark /layla/files/report.pdf scanned
    sudo -E -u www-data php occ files_antivirus:mark /layla/files/report.pdf unscanned

Use `--forever` (`-f`) when marking a file as scanned to permanently exclude it from future rescans:

    sudo -E -u www-data php occ files_antivirus:mark --forever /layla/files/report.pdf scanned

### files_antivirus:scan

Scan a single file immediately and report the result:

    sudo -E -u www-data php occ files_antivirus:scan /layla/files/report.pdf

Use `--debug` to enable verbose backend output, useful when diagnosing scanner connectivity issues:

    sudo -E -u www-data php occ files_antivirus:scan --debug /layla/files/report.pdf

### files_antivirus:status

Show the current antivirus scanner status, including the configured backend and whether the scanner is reachable:

    sudo -E -u www-data php occ files_antivirus:status

Use `-v` for additional backend detail.


# Reference management

The reference management system brings 2 features in Nextcloud:

- [The link previews](/link/947) (also called reference widgets)
- [The Smart Picker](/link/948)

Both those features are generic and need to be extended by the Nextcloud apps.

Apps can add support for some HTTP links so previews are rendered in various places like Text documents and Talk messages.

The Smart Picker is a frontend component which allows users to search or generate links or text.

Apps can register Smart Picker providers to extend its capabilities. Administrators can choose which Smart Picker providers they want to make available to the users by choosing which apps they install. All the Smart Picker providers shipped in the recommended apps do **not** send any data to 3rd party services. Some community apps Smart Picker providers might rely on 3rd party services.

- [Link previews](/link/947)
- [The Smart Picker](/link/948)


# Link previews

Link previews are available in some places in Nextcloud. There are 3 types of link preview:

- The ones for links that are supported by a reference provider  
  - Without custom reference widget (uses a default generic style, image + title + description)
  - With custom reference widget (implemented by the app which supports the link)

- Default ones from OpenGraph information. This is the fallback for every unsupported link

## Where do they appear?

The link previews provided by the Nextcloud reference system appear in the following places:

- Text (and Collectives pages, Notes, Deck card comments, Files comments etc...)  
  - Directly in the document content, next to the links
  - Only one link preview per paragraph is rendered
  - Custom widgets can be rendered

- Talk  
  - In the messages
  - Only one link preview per message is rendered
  - Custom widgets can be rendered

- Nextcloud Office  
  - In the document content when hovering on links
  - Custom widgets are not rendered

## How does it work?

The Nextcloud frontend asks the server to resolve the links via an API request. A rich object is returned as a response and is used by the frontend to render the preview.

The apps can optionally register a custom reference widget to render a specific rich object type (on the links it supports). Therefore the apps have complete freedom over how some previews look like.

## Known link preview providers

- [Collectives](https://github.com/nextcloud/collectives): Links to Collective pages
- [Tables](https://github.com/nextcloud/tables): Links to tables
- [Deck](https://github.com/nextcloud/deck): Links to boards, cards and comments
- [Talk](https://github.com/nextcloud/spreed): Links to conversations
- [GitHub integration](https://github.com/nextcloud/integration_github): Links to GitHub issues, pull requests, comments and repositories
- [GitLab integration](https://github.com/nextcloud/integration_gitlab): Links to Gitlab issues, merge requests, comments and repositories
- [Zammad integration](https://github.com/nextcloud/integration_zammad): Links to Zammad tickets
- [Reddit integration](https://github.com/nextcloud/integration_reddit): Links to subreddits, publications and comments
- [Mastodon integration](https://github.com/nextcloud/integration_mastodon): Links to members and toots
- [The Movie Database integration](https://github.com/nextcloud/integration_tmdb): Links to people, movies and series
- [OpenStreetMap integration](https://github.com/nextcloud/integration_openstreetmap): Location links from OpenStreetMap, Google maps, Bing maps, Here maps and Duckduckgo maps
- [Giphy integration](https://github.com/nextcloud/integration_giphy): Links to GIFs
- [Notion integration](https://github.com/nextcloud/integration_notion): Links to Notion documents
- [Peertube integration](https://github.com/nextcloud/integration_peertube): Links to videos

# The Smart Picker

Every Smart Picker provider can be enabled by installing and configuring the corresponding app.

## Where can it be used?

The Smart Picker can be used in:

- Text (and everywhere Text is used like Collectives pages, Deck card comments, Files comments...): by pressing the "/" key or using a top menu entry
- Talk: by pressing the "/" key in the message composition input
- Nextcloud Office: with a top menu entry (*Insert* → *Pick Link* or *Smart Picker*, depending on Collabora version)
- Mail: in the email composition area with a context menu entry

## Known Smart Picker providers

- Accessing internal data  
  - [Collectives](https://github.com/nextcloud/collectives): To get links to Collective pages
  - [Tables](https://github.com/nextcloud/tables): To get links to tables
  - [Deck](https://github.com/nextcloud/deck): To get links to boards and comments
  - [Talk](https://github.com/nextcloud/spreed): To get links to conversations
  - [Files](https://github.com/nextcloud/server): To get internal links to files (not share links yet)
  - [Text templates](https://github.com/nextcloud/text_templates): To get personal and global text templates

- Relying on 3rd party services  
  - [GitHub integration](https://github.com/nextcloud/integration_github): To get links to GitHub issues, pull requests, and repositories
  - [GitLab integration](https://github.com/nextcloud/integration_gitlab): To get links to Gitlab issues, merge requests, and repositories
  - [Zammad integration](https://github.com/nextcloud/integration_zammad): To get links to Zammad tickets
  - [Reddit integration](https://github.com/nextcloud/integration_reddit): To get links to subreddits and publications
  - [Mastodon integration](https://github.com/nextcloud/integration_mastodon): To get links to members, toots and hashtags
  - [The Movie Database integration](https://github.com/nextcloud/integration_tmdb): To get links to people, movies and series
  - [OpenStreetMap integration](https://github.com/nextcloud/integration_openstreetmap): To get location links from OpenStreetMap
  - [Giphy integration](https://github.com/nextcloud/integration_giphy): To get links to GIFs
  - [Notion integration](https://github.com/nextcloud/integration_notion): To get links to Notion documents
  - [Peertube integration](https://github.com/nextcloud/integration_peertube): To get links to videos
  - [OpenAI integration](https://github.com/nextcloud/integration_openai): To generate images with Dall-e, text with GPT and transcribe/translate with Whisper (speech-to-text)
  - [Replicate integration](https://github.com/nextcloud/integration_replicate): To generate images with stable diffusion, and transcribe/translate with Whisper (speech-to-text)