在树莓派上基于 LNMP 搭建 Nextcloud

最近更新于 2024-09-19 23:17

环境

  • 树莓派CM4
  • raspios 20240704 Debian 12 arm64

搭建 LNMP 环境

安装 Nginx

sudo apt update
sudo apt install -y nginx

安装 php 及功能组件支持

参考:https://docs.nextcloud.com/server/latest/admin_manual/installation/php_configuration.html

sudo apt install -y php php-common php-fpm php-curl php-xml php-fileinfo php-gd php-json php-mbstring php-posix php-simplexml php-xmlreader php-xmlwriter php-zip php-mysql php-intl php-ldap php-ftp php-imap php-bcmath php-gmp php-exif php-apcu php-memcached php-redis php-imagick ffmpeg

安装数据库

MySQL 官方没有提供适用 Debian 12 arm64 的二进制安装包
file

可以自己用 MySQL 社区版源码编译或者找三方编译的安装包,这里使用 MySQL 的开源替代软件 Mariadb,可以直接用官方软件源安装

sudo apt install -y mariadb-server

配置 Nginx 和 PHP 连接

参考:https://docs.nextcloud.com/server/latest/admin_manual/installation/nginx.html#nextcloud-in-the-webroot-of-nginx
以 root 权限编辑 /etc/nginx/sites-available/default,写入(只是模板,需要自己改)
这个配置比较适用配置在公网服务器

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

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

server {
    # http
    listen 80;
    listen [::]:80;
    server_name cloud.example.com; # 自己的域名,IP 访问改为一个下划线

    # Prevent nginx HTTP Server Detection
    server_tokens off;

    # Enforce HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    # https
    # 如果不是部署到公网,就将上一个 server 删掉,把这里的监听 443 端口改为 80,并删掉 **ssl http2**
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    # With NGinx >= 1.25.1 you should use this instead:
    # listen 443      ssl;
    # listen [::]:443 ssl;
    # http2 on;
    server_name cloud.example.com; # 自己的域名,IP 访问改为一个下划线

    # Path to the root of your installation
    # Nextcloud 网站源码放置路径
    root /var/www/nextcloud;

    # Use Mozilla's guidelines for SSL/TLS settings
    # https://mozilla.github.io/server-side-tls/ssl-config-generator/
    # SSL 证书文件路径,配置 https 访问需要,
    ssl_certificate     /etc/nginx/cloud.example.com.crt;
    ssl_certificate_key /etc/nginx/cloud.example.com.key;

    # Prevent nginx HTTP Server Detection
    server_tokens off;

    # HSTS settings
    # WARNING: Only add the preload option once you read about
    # the consequences in https://hstspreload.org/. This option
    # will add the domain to a hardcoded list that is shipped
    # in all major browsers and getting removed from this list
    # could take several months.
    #add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload" always;

    # set max upload size and increase upload timeout:
    client_max_body_size 512M;
    client_body_timeout 300s;
    fastcgi_buffers 64 4K;

    # Enable gzip but do not remove ETag headers
    gzip on;
    gzip_vary on;
    gzip_comp_level 4;
    gzip_min_length 256;
    gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
    gzip_types application/atom+xml text/javascript application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/wasm application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

    # Pagespeed is not supported by Nextcloud, so if your server is built
    # with the `ngx_pagespeed` module, uncomment this line to disable it.
    #pagespeed off;

    # The settings allows you to optimize the HTTP2 bandwidth.
    # See https://blog.cloudflare.com/delivering-http-2-upload-speed-improvements/
    # for tuning hints
    client_body_buffer_size 512k;

    # HTTP response headers borrowed from Nextcloud `.htaccess`
    add_header Referrer-Policy                   "no-referrer"       always;
    add_header X-Content-Type-Options            "nosniff"           always;
    add_header X-Frame-Options                   "SAMEORIGIN"        always;
    add_header X-Permitted-Cross-Domain-Policies "none"              always;
    add_header X-Robots-Tag                      "noindex, nofollow" always;
    add_header X-XSS-Protection                  "1; mode=block"     always;

    # Remove X-Powered-By, which is an information leak
    fastcgi_hide_header X-Powered-By;

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

    # Specify how to handle directories -- specifying `/index.php$request_uri`
    # here as the fallback means that Nginx always exhibits the desired behaviour
    # when a client requests a path that corresponds to a directory that exists
    # on the server. In particular, if that directory contains an index.php file,
    # that file is correctly served; if it doesn't, then the request is passed to
    # the front-end controller. This consistent behaviour means that we don't need
    # to specify custom rules for certain paths (e.g. images and other assets,
    # `/updater`, `/ocs-provider`), and thus
    # `try_files $uri $uri/ /index.php$request_uri`
    # always provides the desired behaviour.
    index index.php index.html /index.php$request_uri;

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

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

    # Make a regex exception for `/.well-known` so that clients can still
    # access it despite the existence of the regex rule
    # `location ~ /(\.|autotest|...)` which would otherwise handle requests
    # for `/.well-known`.
    location ^~ /.well-known {
        # The rules in this block are an adaptation of the rules
        # in `.htaccess` that concern `/.well-known`.

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

        location /.well-known/acme-challenge    { try_files $uri $uri/ =404; }
        location /.well-known/pki-validation    { try_files $uri $uri/ =404; }

        # Let Nextcloud's API for `/.well-known` URIs handle all other
        # requests by passing them to the front-end controller.
        return 301 /index.php$request_uri;
    }

    # Rules borrowed from `.htaccess` to hide certain paths from clients
    location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/)  { return 404; }
    location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console)                { return 404; }

    # Ensure this block, which passes PHP files to the PHP process, is above the blocks
    # which handle static assets (as seen below). If this block is not declared first,
    # then Nginx will encounter an infinite rewriting loop when it prepends `/index.php`
    # to the URI, resulting in a HTTP 500 error response.
    location ~ \.php(?:$|/) {
        # Required for legacy support
        rewrite ^/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|ocs-provider\/.+|.+\/richdocumentscode(_arm64)?\/proxy) /index.php$request_uri;

        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        set $path_info $fastcgi_path_info;

        try_files $fastcgi_script_name =404;

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $path_info;
        fastcgi_param HTTPS on;

        fastcgi_param modHeadersAvailable true;         # Avoid sending the security headers twice
        fastcgi_param front_controller_active true;     # Enable pretty urls
        fastcgi_pass php-handler;

        fastcgi_intercept_errors on;
        fastcgi_request_buffering off;

        fastcgi_max_temp_file_size 0;
    }

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

    location ~ \.woff2?$ {
        try_files $uri /index.php$request_uri;
        expires 7d;         # Cache-Control policy borrowed from `.htaccess`
        access_log off;     # Optional: Don't log access to assets
    }

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

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

安装 Nextcloud

Nextcloud 网站源码下载:https://nextcloud.com/install/
展开社区项目
file
下载 ZIP 包
file

解压得到的 nextcloud 放到 /var/www 路径下,并在这个路径下修改文件权限:https://blog.iyatt.com/?p=14780
后面创建数据库和配置安装和 WordPress 差不多:https://blog.iyatt.com/?p=12732#WordPress_%E5%AE%89%E8%A3%85
只是登录数据库 root 的方式从 mysql -u root -p 改为 sudo mysql

访问页面,首次配置一下数据库连接信息和登录账号
file

然后登录进入页面
file

改进配置

修改 PHP 内存限制值

Nextcloud 建议 php 内存限制至少有 512M,根据自己实际情况调整,我这里树莓派有 8G 内存,直接把 PHP 限制改为 1G
以 root 权限编辑 /etc/php/8.2/fpm/php.ini,路径中的 8.2 是 php 版本,根据自己的实际情况修改
找到 memory_limt 把后面的值修改了
file

然后重启 php-fpm,其中 8.2 换成自己的 php 版本

sudo systemctl restart php8.2-fpm

file

后台任务使用 cron 执行

创建定时任务

sudo crontab -u www-data -e

自己选择一个编辑器,然后写入(/var/www/nextcloud 是网站文件路径)

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

file

然后 Nextcloud 设置 -> 基本设置 -> 后台任务,选择 Cron
file

配置电子邮件服务器(发邮件)

先在设置的个人信息里填上邮箱(用于验证接收)
file

再到基本设置,我这里使用 QQ 邮箱的 STMP 服务来实现发邮件
QQ 邮箱:https://mail.qq.com
获取一个专用的密码
file

file

设置默认电话区域

以 root 权限编辑 Nexcloud 目录下的 config/config.php,追加

'default_phone_region' => 'CN',

file

开启 PHP OPcache

开这个就是把编译过的 PHP 脚本缓存到内存里(内存足够的话),这样可以提升性能。
以 root 权限编辑 /etc/php/8.2/fpm/php.ini,找到 [opcache] 添加下面内容(也可以解开注释编辑参数)

opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.save_comments=1
opcache.revalidate_freq=1

file

重启 PHP-FPM 生效

解决 PHP 访问环境变量

以 root 编辑 /etc/php/8.2/fpm/pool.d/www.conf,找到 env[PATH]
file

去掉前面的分号
file

重启 PHP-FPM 生效

添加缺失的索引(Detected some missing optional indices. 问题)

命令行切换到 Nextcloud 路径下,执行

sudo -u www-data php occ db:add-missing-indices

file

设置维护时间段开始时间

比如将一些复杂操作的时间调整到不常用的时间段,避开使用高峰,默认是任意时间段
以 root 编辑 Nextcloud 目录下的 config/config.php,添加

'maintenance_window_start' => 1,

意味着会从凌晨 1 点开始(持续 4 小时)
file

解决 “您的网络服务器未正确设置来解析 .wellknown URL,失败于: /.well-known/webfinger 更多细节”

我这里出现这个问题是因为使用的端口是非标端口,访问链接后面要指定端口,但是这里的跳转没正确处理
file

以 root 编辑 /etc/nginx/sites-available/default,把上图选中的两行和后面return那行分别修改为

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

        return 301 $scheme://$http_host/index.php$request_uri;

然后重启 Nginx

修改默认存储路径

编辑 Nextcloud 目录下 config/config.php 中的 datadirectory
file

配置局域网代理

如果网络不好,无法访问应用商店
以 root 编辑 Nextcloud 目录下 config/config.php,添加

'proxy' => 'sock5://IP:端口'

'proxy' => 'http://IP:端口'

file

file

插件功能扩展

Two-Factor TOTP Provider【二次验证,一次性密码】

可以绑定 APP,通过 APP 查看一次性密码,在登陆时进行验证
file

file

External storage support 【存储扩展】

可以向 Nextcloud 中添加存储路径,比如挂载了额外的硬盘,把路径添加进去,也能添加其它共享协议或平台
file

Memories 【相册管理】

安装这个插件后,基本功能可以按时间、文件夹、地理位置管理
file

file

反向地理编码下载地球数据库注意

数据库下载后导入时可能处理超时,如果出现超时失败,可以登录数据库,设置延长限制
file

SET GLOBAL wait_timeout = 28800;
SET GLOBAL interactive_timeout = 28800;

图片内容识别功能

可以再安装 Recognize 和 Face Recognition,在此之前最好保证环境配置好

安装 Node.js

# 安装 npm
sudo apt install -y npm

# 安装版本管理工具
sudo npm i -g n

# 更新 Node.js 到最新稳定版
sudo n stable

配置 Composer

# 安装工具
sudo apt install -y build-essential git

# 获取源码
git clone https://github.com/composer/getcomposer.org.git --depth=1 && cd getcomposer/web

# 构建
bash installer

# 拷贝到系统目录
mv composer.phar /usr/local/bin/composer

安装前面提到的两个插件后,管理设置中,配置好 node 路径 /usr/local/bin/node
file

在树莓派上基于 LNMP 搭建 Nextcloud
Scroll to top