
En el artículo de hoy es una traducción de este sitio con información agregada y más organizado para su entendimiento. Vamos a tratar la instalación de Nextcloud sobre un sistema operativo GNU Linux, en este caso Debian. Nextcloud es un software escrito en php, es open source con licencia AGPLv3 dicho software está basado en el paradigma cliente – servidor, en este caso el servidor sería un servidor web con php y el cliente sería un navegador web, aunque también existen clientes de escritorio que se instalarían en un ordenador de “cualquier” tipo, ya que, hay versiones para Microsoft Windows, GNU Linux y MacOs. También existen clientes para móvil tanto para Android e IOS. Nextcloud es similar a el software Dropbox, es decir, Nextcloud tiene la parte de cloud de almacenamiento y compartición de archivos, pero Nextcloud no es solo eso, sino que mediante apps o plugins que podemos instalar junto con Nextcloud podemos hacer que se sea similar a Google Drive o Microsoft Office 365 que en próximos artículos veremos cómo complementar Nextcloud, en este articulo nos centraremos en la instalación del mismo. Pero entonces, ¿cuál es la ventaja de Nextcloud con respecto a sus alternativas? La ventaja principal es que podemos instalarlo en un servidor privado y nadie más que nosotros tiene nuestros datos.
Requisitos:
Para ello deberemos cumplir con unos requisitos previos. Muy importante la «Conexión a Internet» pues usaremos PHP 7.3 que no viene en el repositorio de Debian.
- Contenedor de Proxmox con Debian 9 a 64 bits.
- Necesitamos un mínimo de 128 Mb de Memoria RAM, aunque lo que recomienda la comunidad de Nextcloud es que el servidor tenga un mínimo de 512 Mb, pero mi recomendación es que como mínimo el servidor tenga 1 Gb de memoria RAM.
- Conexión a Internet.
- Instalar PHP 7.3
Requisitos opcionales:
Usar un almacenamiento externo en el cual poner nuestros datos del Nextcloud para que nuestro contenedor de Proxmox no se nos haga inmensamente grande.
- Usar un 2do HDD dentro del mismo Proxmox.
- Usar un compartido de un servidor NFS.
Una vez que tenemos claros y cumplidos los requisitos procedemos con la instalación de Nextcloud:
Corregimos bien el uso horario:
1 | timedatectl set-timezone America/Havana |
Nota.- A un CT de Proxmox no cambiarle la hora, hacerlo directamente en el host Proxmox.
Modificando «/etc/apt/sources.list»:
1 2 3 | su - apt install apt-transport-https git wget gnupg2 dirmngr lsb-release ssl-cert ca-certificates -y mv /etc/apt/sources.list /etc/apt/sources.list.bak ; nano /etc/apt/sources.list |
Incluirle estas líneas:
1 2 3 4 5 6 | deb http://deb.debian.org/debian stretch main deb http://security.debian.org/debian-security stretch/updates main deb [arch=amd64] http://nginx.org/packages/mainline/debian/ stretch nginx deb-src [arch=amd64] http://nginx.org/packages/mainline/debian/ stretch nginx deb [arch=amd64] http://mirror2.hs-esslingen.de/mariadb/repo/10.3/debian stretch main deb https://packages.sury.org/php/ stretch main |
Guardamos y continuamos.
Instalando NGINX:
1 2 3 4 5 6 7 8 9 10 11 | cd /usr/local/src wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg wget http://nginx.org/keys/nginx_signing.key ; apt-key add nginx_signing.key Sin proxy: apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 0xF1656F24C74CD1D8 Con proxy: apt-key adv --keyserver-options http-proxy=http://proxy.dominio.cu:port/ --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys F1656F24C74CD1D8 apt update ; apt upgrade -y apt install software-properties-common zip unzip screen curl git ffmpeg libfile-fcntllock-perl -y apt remove nginx nginx-common nginx-full -y --allow-change-held-packages apt update ; apt install nginx -y |
Modificando NGINX:
1 | systemctl enable nginx.service ; apt-mark hold nginx |
Cambiar configuración de NGINX:
1 | mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak ; nano /etc/nginx/nginx.conf |
Agregue las siguientes líneas:
Modificar el IP de tu LAN.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | user www-data; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; multi_accept on; use epoll; } http { server_names_hash_bucket_size 64; upstream php-handler { server unix:/run/php/php7.3-fpm.sock; } set_real_ip_from 127.0.0.1; set_real_ip_from 192.168.2.0/24; # Rango IP de tu LAN real_ip_header X-Forwarded-For; real_ip_recursive on; include /etc/nginx/mime.types; #include /etc/nginx/proxy.conf; #include /etc/nginx/ssl.conf; #include /etc/nginx/header.conf; #include /etc/nginx/optimization.conf; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" ' '"$host" sn="$server_name" ' 'rt=$request_time ' 'ua="$upstream_addr" us="$upstream_status" ' 'ut="$upstream_response_time" ul="$upstream_response_length" ' 'cs=$upstream_cache_status' ; access_log /var/log/nginx/access.log main; sendfile on; send_timeout 3600; tcp_nopush on; tcp_nodelay on; open_file_cache max=500 inactive=10m; open_file_cache_errors on; keepalive_timeout 65; reset_timedout_connection on; server_tokens off; resolver 8.8.8.8 valid=30s; resolver_timeout 5s; include /etc/nginx/conf.d/*.conf; } |
Reinicia NGINX:
1 | service nginx restart |
Revisar si esta corriendo:
1 | service nginx status |
Para actualizar NGINX en el futuro solo debe introducir la siguiente línea:
1 | apt-mark unhold nginx ; apt upgrade -y ; apt-mark hold nginx |
Crea carpetas y aplica permisos:
Nota.- Los siguientes directorios puedes cambiarlos a conveniencia:
/nextcloud-data = Donde estarán todos los archivos de los usuarios.
/var/www = Donde extraeremos el compactado para instalar Nextcloud.
1 2 3 | mkdir -p /nextcloud-data /var/www/ /usr/local/tmp/cache /usr/local/tmp/sessions /usr/local/tmp/apc /upload_tmp chown -R www-data:www-data /upload_tmp /nextcloud-data /var/www chown -R www-data:root /usr/local/tmp/sessions /usr/local/tmp/cache /usr/local/tmp/apc |
Instalando PHP 7.3:
1 | apt install php7.3-fpm php7.3-gd php7.3-mysql php7.3-curl php7.3-xml php7.3-zip php7.3-intl php7.3-mbstring php7.3-json php7.3-bz2 php7.3-ldap php-apcu imagemagick php-imagick -y |
Configurando PHP:
Para no aburrirlos dando «Enter» a cada una de las líneas las pondremos a continuación de un «;» para hacerlo mas rápido:
1 | cp /etc/php/7.3/fpm/pool.d/www.conf /etc/php/7.3/fpm/pool.d/www.conf.bak ; cp /etc/php/7.3/cli/php.ini /etc/php/7.3/cli/php.ini.bak ; cp /etc/php/7.3/fpm/php.ini /etc/php/7.3/fpm/php.ini.bak ; cp /etc/php/7.3/fpm/php-fpm.conf /etc/php/7.3/fpm/php-fpm.conf.bak |
1 | sed -i "s/;env\[HOSTNAME\] = /env[HOSTNAME] = /" /etc/php/7.3/fpm/pool.d/www.conf ; sed -i "s/;env\[TMP\] = /env[TMP] = /" /etc/php/7.3/fpm/pool.d/www.conf ; sed -i "s/;env\[TMPDIR\] = /env[TMPDIR] = /" /etc/php/7.3/fpm/pool.d/www.conf ; sed -i "s/;env\[TEMP\] = /env[TEMP] = /" /etc/php/7.3/fpm/pool.d/www.conf ; sed -i "s/;env\[PATH\] = /env[PATH] = /" /etc/php/7.3/fpm/pool.d/www.conf ; sed -i "s/pm.max_children = .*/pm.max_children = 240/" /etc/php/7.3/fpm/pool.d/www.conf ; sed -i "s/pm.start_servers = .*/pm.start_servers = 20/" /etc/php/7.3/fpm/pool.d/www.conf ; sed -i "s/pm.min_spare_servers = .*/pm.min_spare_servers = 10/" /etc/php/7.3/fpm/pool.d/www.conf ; sed -i "s/pm.max_spare_servers = .*/pm.max_spare_servers = 20/" /etc/php/7.3/fpm/pool.d/www.conf ; sed -i "s/;pm.max_requests = 500/pm.max_requests = 500/" /etc/php/7.3/fpm/pool.d/www.conf ; sed -i "s/output_buffering =.*/output_buffering = 'Off'/" /etc/php/7.3/cli/php.ini ; sed -i "s/max_execution_time =.*/max_execution_time = 1800/" /etc/php/7.3/cli/php.ini ; sed -i "s/max_input_time =.*/max_input_time = 3600/" /etc/php/7.3/cli/php.ini ; sed -i "s/post_max_size =.*/post_max_size = 10240M/" /etc/php/7.3/cli/php.ini ; sed -i "s/;upload_tmp_dir =.*/upload_tmp_dir = \/upload_tmp/" /etc/php/7.3/cli/php.ini ; sed -i "s/upload_max_filesize =.*/upload_max_filesize = 10240M/" /etc/php/7.3/cli/php.ini ; sed -i "s/max_file_uploads =.*/max_file_uploads = 100/" /etc/php/7.3/cli/php.ini ; sed -i "s/;date.timezone.*/date.timezone = America\/\Havana/" /etc/php/7.3/cli/php.ini ; sed -i "s/;session.cookie_secure.*/session.cookie_secure = True/" /etc/php/7.3/cli/php.ini ; sed -i "s/;session.save_path =.*/session.save_path = \"N;700;\/usr\/local\/tmp\/sessions\"/" /etc/php/7.3/cli/php.ini ; sed -i '$aapc.enable_cli = 1' /etc/php/7.3/cli/php.ini ; sed -i "s/memory_limit = 128M/memory_limit = 512M/" /etc/php/7.3/fpm/php.ini ; sed -i "s/output_buffering =.*/output_buffering = 'Off'/" /etc/php/7.3/fpm/php.ini ; sed -i "s/max_execution_time =.*/max_execution_time = 1800/" /etc/php/7.3/fpm/php.ini ; sed -i "s/max_input_time =.*/max_input_time = 3600/" /etc/php/7.3/fpm/php.ini ; sed -i "s/post_max_size =.*/post_max_size = 10240M/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;upload_tmp_dir =.*/upload_tmp_dir = \/upload_tmp/" /etc/php/7.3/fpm/php.ini ; sed -i "s/upload_max_filesize =.*/upload_max_filesize = 10240M/" /etc/php/7.3/fpm/php.ini ; sed -i "s/max_file_uploads =.*/max_file_uploads = 100/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;date.timezone.*/date.timezone = America\/\Havana/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;session.cookie_secure.*/session.cookie_secure = True/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;opcache.enable=.*/opcache.enable=1/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;opcache.enable_cli=.*/opcache.enable_cli=1/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;opcache.memory_consumption=.*/opcache.memory_consumption=128/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;opcache.interned_strings_buffer=.*/opcache.interned_strings_buffer=8/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;opcache.max_accelerated_files=.*/opcache.max_accelerated_files=10000/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;opcache.revalidate_freq=.*/opcache.revalidate_freq=1/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;opcache.save_comments=.*/opcache.save_comments=1/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;session.save_path =.*/session.save_path = \"N;700;\/usr\/local\/tmp\/sessions\"/" /etc/php/7.3/fpm/php.ini ; sed -i "s/;emergency_restart_threshold =.*/emergency_restart_threshold = 10/" /etc/php/7.3/fpm/php-fpm.conf ; sed -i "s/;emergency_restart_interval =.*/emergency_restart_interval = 1m/" /etc/php/7.3/fpm/php-fpm.conf ; sed -i "s/;process_control_timeout =.*/process_control_timeout = 10s/" /etc/php/7.3/fpm/php-fpm.conf ; sed -i '$aapc.enabled=1' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.file_update_protection=2' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.optimization=0' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.shm_size=256M' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.include_once_override=0' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.shm_segments=1' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.ttl=7200' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.user_ttl=7200' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.gc_ttl=3600' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.num_files_hint=1024' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.enable_cli=0' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.max_file_size=5M' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.cache_by_default=1' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.use_request_time=1' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.slam_defense=0' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.mmap_file_mask=/usr/local/tmp/apc.XXXXXX' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.stat_ctime=0' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.canonicalize=1' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.write_lock=1' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.report_autofilter=0' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.rfc1867=0' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.rfc1867_prefix =upload_' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.rfc1867_name=APC_UPLOAD_PROGRESS' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.rfc1867_freq=0' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.rfc1867_ttl=3600' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.lazy_classes=0' /etc/php/7.3/fpm/php.ini ; sed -i '$aapc.lazy_functions=0' /etc/php/7.3/fpm/php.ini |
Además, estas 2 para el cron (cada una es una línea independiente):
1 2 | sed -i "s/09,39.*/# &/" /etc/cron.d/php (crontab -l ; echo "09,39 * * * * /usr/lib/php/sessionclean 2>&1") | crontab -u root - |
Modifica /etc/fstab:
Determine el uid de su usuario www-data con:
1 | id www-data |
Y solo si difiere de «uid=33» reemplaza el «uid=33» en las siguientes filas correctamente antes de ejecutarlas!
1 2 3 | sed -i '$atmpfs /usr/local/tmp/apc tmpfs defaults,uid=33,size=300M,noatime,nosuid,nodev,noexec,mode=1777 0 0' /etc/fstab sed -i '$atmpfs /usr/local/tmp/cache tmpfs defaults,uid=33,size=300M,noatime,nosuid,nodev,noexec,mode=1777 0 0' /etc/fstab sed -i '$atmpfs /usr/local/tmp/sessions tmpfs defaults,uid=33,size=300M,noatime,nosuid,nodev,noexec,mode=1777 0 0' /etc/fstab |
Opcional:
12 sed -i '$atmpfs /tmp tmpfs defaults,noatime,nosuid,nodev,noexec,mode=1777 0 0' /etc/fstabsed -i '$atmpfs /var/tmp tmpfs defaults,noatime,nosuid,nodev,noexec,mode=1777 0 0' /etc/fstab
Monte tmpfs y luego reinicie ambos, PHP y NGINX:
1 | mount -a ; service php7.3-fpm restart ; service nginx restart |
Instalando MariaDB:
1 | apt update ; apt install mariadb-server -y |
Nota.- Debe salir una pantalla azul y una caja en la cual introduciremos la contraseña para el usuario «root» de MariaDB. Y la repetimos.
Verifique la versión de su servidor de base de datos:
1 2 | mysql --version mysql Ver 15.1 Distrib 10.3.12-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2 |
Asegurar MariaDB:
1 2 3 4 5 6 7 8 | mysql_secure_installation Enter current password for root (enter for none): Set root password? [Y/n] n Remove anonymous users? [Y/n] Y Disallow root login remotely? [Y/n] Y Remove test database and access to it? [Y/n] Y Reload privilege tables now? [Y/n] Y |
Configure MariaDB:
1 2 | service mysql stop mv /etc/mysql/my.cnf /etc/mysql/my.cnf.bak ; nano /etc/mysql/my.cnf |
Agregue las siguientes líneas:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | [client] port = 3306 socket = /var/run/mysqld/mysqld.sock default-character-set = utf8 [mysqld_safe] log_error=/var/log/mysql/mysql_error.log socket = /var/run/mysqld/mysqld.sock nice = 0 [mysqld] user = mysql pid-file = /var/run/mysqld/mysqld.pid log_error=/var/log/mysql/mysql_error.log general_log_file = /var/log/mysql/mysql.log general_log = 0 socket = /var/run/mysqld/mysqld.sock port = 3306 basedir = /usr datadir = /var/lib/mysql tmpdir = /tmp lc_messages_dir = /usr/share/mysql lc_messages = en_US skip-external-locking skip-name-resolve bind-address = 127.0.0.1 max_connections = 200 connect_timeout = 5 wait_timeout = 600 max_allowed_packet = 16M thread_cache_size = 128 sort_buffer_size = 4M bulk_insert_buffer_size = 16M tmp_table_size = 64M max_heap_table_size = 64M myisam_recover_options = BACKUP key_buffer_size = 128M #open-files-limit = 2000 table_open_cache = 400 myisam_sort_buffer_size = 512M concurrent_insert = 2 read_buffer_size = 2M read_rnd_buffer_size = 1M query_cache_limit = 2M query_cache_size = 64M query_cache_type = 1 query_cache_min_res_unit = 2k log_warnings = 2 slow_query_log_file = /var/log/mysql/mariadb-slow.log long_query_time = 1 log_slow_verbosity = query_plan slow-query-log = 1 slow-query-log-file = /var/log/mysql/slow.log log_bin = /var/log/mysql/mariadb-bin log_bin_index = /var/log/mysql/mariadb-bin.index expire_logs_days = 10 max_binlog_size = 100M default_storage_engine = InnoDB innodb_buffer_pool_size = 1024M innodb_buffer_pool_instances = 1 innodb_flush_log_at_trx_commit = 2 innodb_log_buffer_size = 32M innodb_max_dirty_pages_pct = 90 innodb_file_per_table = 1 innodb_open_files = 400 innodb_io_capacity = 4000 innodb_flush_method = O_DIRECT character-set-server = utf8 collation-server = utf8_general_ci transaction_isolation = READ-COMMITTED binlog_format = ROW [mysqldump] quick quote-names max_allowed_packet = 16M [mysql] #no-auto-rehash # faster start of mysql but no tab completion [isamchk] key_buffer = 16M !include /etc/mysql/mariadb.cnf !includedir /etc/mysql/conf.d/ |
Reinicie el servicio y conéctese a MariaDB:
1 | service mysql restart |
Crea la base de datos y el usuario:
1 | mysql -uroot -p |
Nota.- Contraseña de MariaDB
Base de datos = nextcloud
Usuario para conectarse a la Base de datos = nextcloud
Password = passw0rd (o la que usted desee)
1 2 3 4 5 | CREATE DATABASE nextcloud CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE USER nextcloud@localhost identified by 'miclave'; GRANT ALL PRIVILEGES on nextcloud.* to nextcloud@localhost; FLUSH privileges; quit; |
Verifique que «transaction Isolation level» se haya establecido a READ_COMMITTED y la colación se estableció en UTF8MB4 correctamente:
1 | mysql -h localhost -uroot -p -e "SELECT @@TX_ISOLATION; SELECT SCHEMA_NAME 'database', default_character_set_name 'charset', DEFAULT_COLLATION_NAME 'collation' FROM information_schema.SCHEMATA WHERE SCHEMA_NAME='nextcloud'" |
Introducimos el password de MariaDB y debe devolvernos algo como esto:
1 2 3 4 5 6 7 8 9 10 | +---------------------+ | @@TX_ISOLATION | +---------------------+ | READ-COMMITTED | +---------------------+ +-----------+---------+--------------------+ | database | charset | collation | +-----------+---------+--------------------+ | nextcloud | utf8 | utf8_general_ci | +-----------+---------+--------------------+ |
Si el conjunto de resultados fue «READ-COMMITTED» y «utf8_general_ci» como se muestra, continúe con la instalación de redis.
Instalando Redis:
1 | apt update ; apt install redis-server php-redis -y |
Cambiar configuración y pertenencia a grupos:
1 2 3 4 | cp /etc/redis/redis.conf /etc/redis/redis.conf.bak sed -i "s/port 6379/port 0/" /etc/redis/redis.conf ; sed -i s/\#\ unixsocket/\unixsocket/g /etc/redis/redis.conf ; sed -i "s/unixsocketperm 700/unixsocketperm 770/" /etc/redis/redis.conf ; sed -i "s/# maxclients 10000/maxclients 512/" /etc/redis/redis.conf usermod -a -G redis www-data cp /etc/sysctl.conf /etc/sysctl.conf.bak ; sed -i '$avm.overcommit_memory = 1' /etc/sysctl.conf |
Reinicie su servidor:
1 | reboot |
Nextcloud:
Creando nextcloud.conf
1 2 | su - mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.bak ; nano /etc/nginx/conf.d/nextcloud.conf |
Agregue las siguientes líneas:
Modificar los dos «SERVIDOR.DOMINIO.CU», y si vas a permitir redes sociales buscar las líneas que hablan al respecto.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | server { server_name SERVIDOR.DOMINIO.CU; # Modificar listen 80 default_server; location ^~ /.well-known/acme-challenge { proxy_pass http://127.0.0.1:81; proxy_set_header Host $host; } location / { return 301 https://$host$request_uri; } } server { server_name SERVIDOR.DOMINIO.CU; # Modificar listen 443 ssl http2 default_server; root /var/www/nextcloud/; access_log /var/log/nginx/nextcloud.access.log main; error_log /var/log/nginx/nextcloud.error.log warn; location = /robots.txt { allow all; log_not_found off; access_log off; } location = /.well-known/carddav { return 301 $scheme://$host/remote.php/dav; } location = /.well-known/caldav { return 301 $scheme://$host/remote.php/dav; } #Redes Sociales habilitadas? Por favor descomenta las siguientes tres filas #rewrite ^/.well-known/webfinger /public.php?service=webfinger last; #rewrite ^/.well-known/host-meta /public.php?service=host-meta last; #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json last; client_max_body_size 10240M; location / { rewrite ^ /index.php$uri; } location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)/ { deny all; } location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) { deny all; } location ~ \.(?:flv|mp4|mov|m4a)$ { mp4; mp4_buffer_size 100M; mp4_max_buffer_size 1024M; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; include php_optimization.conf; fastcgi_pass php-handler; fastcgi_param HTTPS on; } location ~ ^/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+)\.php(?:$|/) { fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; include php_optimization.conf; fastcgi_pass php-handler; fastcgi_param HTTPS on; } location ~ ^/(?:updater|ocs-provider)(?:$|/) { try_files $uri/ =404; index index.php; } location ~ \.(?:css|js|woff2?|svg|gif|png|html|ttf|ico|jpg|jpeg)$ { try_files $uri /index.php$uri$is_args$args; access_log off; expires 360d; } } |
Si desea que su Nextcloud se ejecute en un subdirectorio como «https://servidor.dominio.cu/nextcloud«, use este nextcloud.conf en su lugar:
Modificar los dos «SERVIDOR.DOMINIO.CU», y si vas a permitir redes sociales buscar las líneas que hablan al respecto.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | server { server_name SERVIDOR.DOMINIO.CU; # Modificar listen 80 default_server; location ^~ /.well-known/acme-challenge { proxy_pass http://127.0.0.1:81; proxy_set_header Host $host; } location / { return 301 https://$host$request_uri; } } server { server_name SERVIDOR.DOMINIO.CU; # Modificar listen 443 ssl http2 default_server; root /var/www/; access_log /var/log/nginx/nextcloud.access.log main; error_log /var/log/nginx/nextcloud.error.log warn; location = /robots.txt { allow all; log_not_found off; access_log off; } location = /.well-known/carddav { return 301 $scheme://$host/nextcloud/remote.php/dav; } location = /.well-known/caldav { return 301 $scheme://$host/nextcloud/remote.php/dav; } #Redes Sociales habilitadas? Por favor descomenta las siguientes tres filas #rewrite ^/.well-known/webfinger /nextcloud/public.php?service=webfinger last; #rewrite ^/.well-known/host-meta /nextcloud/public.php?service=host-meta last; #rewrite ^/.well-known/host-meta.json /nextcloud/public.php?service=host-meta-json last; client_max_body_size 10240M; location ^~ /nextcloud { location /nextcloud { rewrite ^ /nextcloud/index.php$uri; } location ~ ^/nextcloud/(?:build|tests|config|lib|3rdparty|templates|data)/ { deny all; } location ~ ^/nextcloud/(?:\.|autotest|occ|issue|indie|db_|console) { deny all; } location ~ \.(?:flv|mp4|mov|m4a)$ { mp4; mp4_buffer_size 100M; mp4_max_buffer_size 1024M; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; include php_optimization.conf; fastcgi_pass php-handler; fastcgi_param HTTPS on; } location ~ ^/nextcloud/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+)\.php(?:$|/) { fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; include php_optimization.conf; fastcgi_pass php-handler; fastcgi_param HTTPS on; } location ~ ^/nextcloud/(?:updater|ocs-provider)(?:$|/) { try_files $uri/ =404; index index.php; } location ~ \.(?:png|html|ttf|ico|jpg|jpeg|css|js|woff2?|svg|gif)$ { try_files $uri /nextcloud/index.php$uri$is_args$args; access_log off; expires 360d; } } } |
Ahora crearemos el certificado SSL:
1 2 3 4 | mkdir /etc/nginx/certificados ; cd /etc/nginx/certificados apt install openssl openssl genrsa -out nextcloud.key 2048 openssl req -new -key nextcloud.key -out nextcloud.csr |
Al ejecutar este comando vendrán una serie de preguntas las cuales voy a explicar a continuación:
En caso de equivocación presionar Ctrl + C para cancelar, introducir el comando anterior y volver a empezar.
Country Name (2 letter code) = Código de país en formato ISO de dos letras.
State or Province Name (full name) = Estado o provincia.
Locality Name = Localidad o ciudad.
Organization Name = Nombre de la organización.
Organizational Unit Name = Sector de la organización.
Common Name = FQDN del servidor. Introducir el DNS para tu nextcloud (nextcloud.dominio.cu).
Email Address = Dirección de correo de contacto. (o Enter para no poner nada)
A los campos «A challenge password» y «An optional company name» dale Enter para dejarlos en blanco.
Generamos el certificado para 10 años:
1 | openssl x509 -req -days 3652 -in nextcloud.csr -signkey nextcloud.key -out nextcloud.crt |
Crea el ssl.conf:
1 | nano /etc/nginx/ssl.conf |
Agregale las líneas siguientes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | ssl_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem; ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key; ssl_trusted_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem; ssl_certificate /etc/nginx/certificados/nextcloud.crt; ssl_certificate_key /etc/nginx/certificados/nextcloud.key; #ssl_trusted_certificate /etc/nginx/certificados/chain.pem; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_protocols TLSv1.2; ssl_ciphers 'ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384'; ssl_ecdh_curve secp521r1:secp384r1:prime256v1; ssl_prefer_server_ciphers on; ssl_stapling on; ssl_stapling_verify on; |
Crea el proxy.conf:
1 | nano /etc/nginx/proxy.conf |
Agregale las líneas siguientes:
1 2 3 4 5 6 7 8 9 10 11 | proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Protocol $scheme; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Port $server_port; proxy_set_header X-Forwarded-Server $host; proxy_connect_timeout 3600; proxy_send_timeout 3600; proxy_read_timeout 3600; proxy_redirect off; |
Crea el header.conf:
1 | nano /etc/nginx/header.conf |
Agregale las líneas siguientes:
Modificar en la última linea «servidor.dominio.cu» por el FQDN de tu servidor Nextcloud y mantener el «https».
1 2 3 4 5 6 7 8 | add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;"; add_header X-Robots-Tag none; add_header X-Download-Options noopen; add_header X-Permitted-Cross-Domain-Policies none; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "no-referrer" always; add_header Feature-Policy "accelerometer 'none'; autoplay 'self'; geolocation 'none'; midi 'none'; notifications 'self'; push 'self'; sync-xhr 'self' https://your.dedyn.io; microphone 'self'; camera 'self'; magnetometer 'none'; gyroscope 'none'; speaker 'self'; vibrate 'self'; fullscreen 'self'; payment 'none'; usb 'none'"; |
Crea el optimization.conf:
1 | nano /etc/nginx/optimization.conf |
Agregale las líneas siguientes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fastcgi_read_timeout 3600; fastcgi_buffers 64 64K; fastcgi_buffer_size 256k; fastcgi_busy_buffers_size 3840K; fastcgi_cache_key $http_cookie$request_method$host$request_uri; fastcgi_cache_use_stale error timeout invalid_header http_500; fastcgi_ignore_headers Cache-Control Expires Set-Cookie; gzip on; gzip_vary on; gzip_comp_level 4; gzip_min_length 256; gzip_proxied expired no-cache no-store private no_last_modified no_etag auth; gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy; gzip_disable "MSIE [1-6]\."; |
Crea el php_optimization.conf:
1 | nano /etc/nginx/php_optimization.conf |
Agregale las líneas siguientes:
1 2 3 4 5 6 7 8 9 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param modHeadersAvailable true; fastcgi_param front_controller_active true; fastcgi_intercept_errors on; fastcgi_request_buffering off; fastcgi_cache_valid 404 1m; fastcgi_cache_valid any 1h; fastcgi_cache_methods GET HEAD; |
Modificar NGINX para usar los nuevos archivos que creamos (proxy, ssl, header y optimization), y lo reiniciamos:
1 | sed -i s/\#\include/\include/g /etc/nginx/nginx.conf ; service nginx restart |
Revisamos nuevamente su estado:
1 | service nginx status |
Descargar y extraer Nextcloud:
1 2 3 | cd /var/www wget https://download.nextcloud.com/server/releases/latest.tar.bz2 tar -xjf latest.tar.bz2 -C /var/www ; chown -R www-data:www-data /var/www/ |
Nota.- Si lo tienes descargado ya copialo al servidor usando un cliente SFTP
Si lo tienes en .zip:
1 2 | cd /var/www unzip nextcloud-15.0.2.zip ; chown -R www-data:www-data /var/www/ |
Justo antes de instalar haremos un paréntesis para quienes quieran usar un almacenamiento externo ya quede instalado Nextcloud dentro de dicho almacenamiento.
- Usando un 2do HDD dentro del mismo Proxmox haremos lo siguiente:
Apagamos el contenedor:
1 | shutdown -h now |
Nos conectamos al host Proxmox y realizamos estos pasos.
Asumiremos que usted solo tiene conectado el HDD sin montar y el sistema lo nombró sdb, en caso de tenerlo ya montado desmóntelo y use la ruta /nextcloud-data.
Listamos los HDD
1 2 3 4 5 6 | NAME FSTYPE LABEL UUID MOUNTPOINT NAME SIZE OWNER GROUP MODE sda sda 298,1G root disk brw-rw---- ├─sda1 ext4 456601bc-efa4-450c-b380-2441e3a351f0 / ├─sda1 294,1G root disk brw-rw---- ├─sda2 ├─sda2 1K root disk brw-rw---- └─sda5 swap a964f87b-4f06-4a08-bafb-e5f29ca049f8 [SWAP] └─sda5 4G root disk brw-rw---- sdb ext4 d515e96b-d282-4ae2-9776-385e447e67fd sdb 931,5G root disk brw-rw---- |
Si como dijimos, no lo tiene montado, en la parte de «MountPoint» para «sdb» no saldrá nada.
(Si el HDD es nuevo) Formateamos el HDD en Ext4:
1 | mkfs.ext4 /dev/sdb |
Creamos un directorio en el cual montaremos el nuevo HDD. Montamos y corregimos permisos:
1 2 3 | mkdir /nextcloud-data mount /dev/sdb /nextcloud-data/ chown -R www-data:www-data /nextcloud-data |
Editamos el fstab para montar automáticamente el nuevo disco cuando arranque nuestro proxmox.
1 2 3 | nano /etc/fstab ----------------------------------------------- /dev/sdb /nextcloud-data ext4 defaults 0 1 |
Modificamos el archivo de configuración de nuestro contenedor (sustituir ID):
1 | nano /etc/pve/lxc/ID.conf |
Debajo de la línea «memory» agregamos lo siguiente:
1 | mp0: /nextcloud-data,mp=/nextcloud-data |
Nota.- Directorio de Proxmox mapeado a la carpeta /nextcloud-data del contenedor. La información la guardaras directamente en el 2do HDD del Proxmox.
Listo! Iniciamos el contenedor nuevamente y continuamos con la Instalación del Nextcloud.
- Usando un compartido NFS:
Apagamos el contenedor:
1 | shutdown -h now |
Si usted tiene un servidor NFS en su red también puede usarlo para guardar los datos de su Nextcloud. Para ello realizamos estos pasos.
Asumiremos que usted sabe trabajar con su servidor NFS y que ya creó el directorio que va a compartir y modificó el archivo «/etc/exports» del NFS donde agrego el IP de su servidor Nextcloud.
Un ejemplo de o que se debería agregar al exports:
/nextcloud-data/ 192.168.2.1(rw,no_wdelay,async,no_root_squash,no_subtree_check)
Luego de esto le realizaremos unos cambios al APP ARMOR del host Proxmox donde se encuentra nuestro Nextcloud para que los Contenedores puedan conectarse al NFS.
Si su Proxmox es version 4.4.x:
1 | nano /etc/apparmor.d/lxc/lxc-default-cgns |
Y agregamos antes del «}» final:
1 2 3 | allow mount fstype=nfs, allow mount fstype=nfs4, allow mount fstype=rpc_pipefs, |
Si su Proxmox es version 5.2.x:
1 | nano /etc/apparmor.d/lxc/lxc-default-cgns |
Agregamos antes del «}» final:
1 2 3 | mount fstype=nfs, mount fstype=nfs4, mount fstype=rpc_pipefs, |
Y además en el archivo de configuración del contenedor:
1 | nano /etc/pve/lxc/ID.conf |
Agregamos las siguientes lineas al final:
1 2 | lxc.apparmor.profile: lxc-default-cgns lxc.apparmor.profile: unconfined |
Luego de acomodar el APP ARMOR instalamos el cliente NFS en el contenedor de Nextcloud:
1 | apt install nfs-common |
Creamos el archivo «rc.local» si no está, y le damos permisos:
1 2 | touch /etc/rc.local chmod -R 755 /etc/rc.local |
Agregarle al «rc.local» el comando para que monte el compartido del NFS cuando se inicie:
1 | nano /etc/rc.local |
Agregarle:
1 2 | #!/bin/bash mount -t nfs 192.168.2.1:/nextcloud-data /nextcloud-data |
Iniciamos el contenedor y revisamos si se montó bien el compartido con el siguiente comando:
1 2 3 | lsblk -fm NAME FSTYPE LABEL UUID MOUNTPOINT NAME SIZE OWNER GROUP MODE sdb /nextcloud-data sdb 931.5G |
Listo! Ahí tenemos nuestro compartido NFS listo para utilizar.
Continuamos con la instalación…
Instala Nextcloud silenciosamente:
Información:
-database-name «nextcloud»: La creamos anteriormente configurando base de datos y usuario.
-database-user «nextcloud»: Lo creamos anteriormente configurando base de datos y usuario.
-database-pass «passw0rd»: La que pusimos anteriormente configurando base de datos y usuario.
-admin-user «UsuarioAdmin»: Nombre de usuario para administrar Nextcloud, el que guste.
-admin-pass «PassswordAdmin»: Contraseña del usuario de administración, la que guste.
-data-dir «/nextcloud-data»: Si modificaste al inicio del manual esta dirección, sustituyala.
1 | su - www-data -s /bin/bash -c 'php /var/www/nextcloud/occ maintenance:install --database "mysql" --database-name "nextcloud" --database-user "nextcloud" --database-pass "passw0rd" --admin-user "UsuarioAdmin" --admin-pass "PassswordAdmin" --data-dir "/nextcloud-data"' |
Modifica las líneas para tu dominio:
1 2 | su - www-data -s /bin/bash -c 'php /var/www/nextcloud/occ config:system:set trusted_domains 1 --value=nextcloud.dominio.cu' su - www-data -s /bin/bash -c 'php /var/www/nextcloud/occ config:system:set overwrite.cli.url --value=https://nextcloud.dominio.cu' |
Si vas a acceder al Nextcloud por el IP agregamos también:
1 | su - www-data -s /bin/bash -c 'php /var/www/nextcloud/occ config:system:set trusted_domains 2 --value=192.168.2.1' |
Hacemos una copia de la configuración:
1 | cp /var/www/nextcloud/config/config.php /var/www/nextcloud/config/config.php.bak |
Amplía tu config.php de Nextcloud:
1 2 | sed -i 's/^[ ]*//' /var/www/nextcloud/config/config.php ; sed -i '/);/d' /var/www/nextcloud/config/config.php nano /var/www/nextcloud/config/config.php |
Agrega las siguientes líneas a continuación de las que aparecen:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 'activity_expire_days' => 14, 'auth.bruteforce.protection.enabled' => true, 'blacklisted_files' => array ( 0 => '.htaccess', 1 => 'Thumbs.db', 2 => 'thumbs.db', ), 'cron_log' => true, 'enable_previews' => true, 'enabledPreviewProviders' => array ( 0 => 'OC\\Preview\\PNG', 1 => 'OC\\Preview\\JPEG', 2 => 'OC\\Preview\\GIF', 3 => 'OC\\Preview\\BMP', 4 => 'OC\\Preview\\XBitmap', 5 => 'OC\\Preview\\Movie', 6 => 'OC\\Preview\\PDF', 7 => 'OC\\Preview\\MP3', 8 => 'OC\\Preview\\TXT', 9 => 'OC\\Preview\\MarkDown', ), 'filesystem_check_changes' => 0, 'filelocking.enabled' => 'true', 'htaccess.RewriteBase' => '/', 'integrity.check.disabled' => false, 'knowledgebaseenabled' => false, 'logfile' => '/nextcloud-data/nextcloud.log', 'loglevel' => 2, 'logtimezone' => 'America/Havana', 'log_rotate_size' => 104857600, 'maintenance' => false, 'memcache.local' => '\\OC\\Memcache\\APCu', 'memcache.locking' => '\\OC\\Memcache\\Redis', 'overwriteprotocol' => 'https', 'preview_max_x' => 1024, 'preview_max_y' => 768, 'preview_max_scale_factor' => 1, 'redis' => array ( 'host' => '/var/run/redis/redis.sock', 'port' => 0, 'timeout' => 0.0, ), 'quota_include_external_storage' => false, 'share_folder' => '/Shares', 'skeletondirectory' => '', 'theme' => '', 'trashbin_retention_obligation' => 'auto, 7', 'updater.release.channel' => 'stable', ); |
Edita el .user.ini de Nextcloud:
1 | sed -i "s/upload_max_filesize=.*/upload_max_filesize=10240M/" /var/www/nextcloud/.user.ini ; sed -i "s/post_max_size=.*/post_max_size=10240M/" /var/www/nextcloud/.user.ini ; sed -i "s/output_buffering=.*/output_buffering='Off'/" /var/www/nextcloud/.user.ini |
Reinicia servicios:
1 |