Nextcloud

Create your own Nextcloud instance with Apache

published on

Note: This post has now been superseded by Installing your own Nextcloud instance in 2024. It is advised to used the newer post to install Nextcloud.

Nextcloud is often used by people as somewhere to store their files but it can be used for much more than this.

Nextcloud can also be used to store your contacts, calanders, notes, todo lists and read your mail besides a wide range of other features that can be easily added if required.

Here I will show you how to install Nextcloud using Apache.

Perform initial setup

sudo apt install lsb-release ca-certificates apt-transport-https software-properties-common language-pack-en-base unzip zip curl
sudo add-apt-repository ppa:ondrej/php
sudo add-apt-repository ppa:ondrej/apache2
sudo apt update

Now install PHP

We also install a few other utilities to support tasks that Nextcloud may perform depending on how you choose to use it.

sudo apt install php8.0-{common, cli, bz2, zip, curl, intl, mysql, snmp, memcached, imagick, gd, imap, ldap, soap, tidy, xml, gmp, pspell, mbstring, opcache, fpm, ssh2, imap, redis, apcu, mcrypt, smbclient, bcmath}
sudo apt install ghostscript imagemagick ffmpeg

Now we will configure PHP

Now run sudo nano /etc/php/8.0/fpm/pool.d/www.conf and add or alter lines to read as below

listen = /run/php/php8.0-fpm.sock
listen.owner = www-data
listen.mode = 0660
env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp

You will also need to edit the php.ini files (/etc/php/8.0/fpm/php.ini and /etc/php/8.0/cli/php.ini) to ensure the following lines are present

output_buffering = Off
zlib.output_compression On
zlib.output_compression_level 5
expose_php = off
max_execution_time = 60
max_input_time = 60
max_input_vars = 1000
memory_limit = 512M
post_max_size = 8M
upload_max_filesize = 20M
allow_url_fopen = Off
date.timezone = Europe/London
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=32
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.save_comments=1
opcache.jit_buffer_size=100M
opcache.jit=1255

Finally run sudo systemctl restart php8.0-fpm to make sure PHP is using your new settings.

Now install Redis server

Once Redis is installed we will set it up as a cache which will help to speed up access times. To do so run sudo apt install redis-server php-redis and edit /etc/redis/redis.conf to add or change the following lines

Find the line that starts with'bind 127.0.0.1 ::1' and uncomment it
Look for an option called'supervised' and change it to 'systemd'
Look for the 'maxmemory' line and change it to 'maxmemory 256mb'
Look for the 'maxmemory-policy' line and change it to 'maxmemory-policy allkeys-lru'

Now make the log directory by running sudo mkdir -p /var/log/redis and make sure Redis can access it by running sudo chown redis:redis /var/log/redis.

Finally, make sure Redis will start on boot and use the settings you have just changed:

sudo systemctl enable redis-server
sudo systemctl restart redis.service

It's time to install the MariaDB database

Run sudo apt install mariadb-server mariadb-backup to install everything you need and then make sure to secure it by running sudo mysql_secure_installation.

Edit the file at /etc/mysql/mariadb.conf.d/50-server.cnf and make the changes below

bind-address 127.0.0.1
local-infile=0

Once this is done run sudo mysql -u root -p and create a database with the following commands

CREATE DATABASE nextcloud CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE USER 'nc'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON nextcloud.* TO 'nc'@'localhost';
FLUSH PRIVILEGES;
exit

Now install the Apache web server

sudo apt install apache2 apache2-utils libapache2-mod-fcgid
sudo a2enmod mime http2 rewrite deflate expires headers ssl setenvif dir env proxy_fcgi

Edit the /etc/apache2/conf-enabled/security.conf file and add or change the following lines

ServerTokens Prod
ServerSignature Off
TraceEnable Off
Header unset ETag
FileETag None
Header unset Server
Header always unset X-Powered-By
Header unset X-CF-Powered-By
Header unset X-Mod-Pagespeed
Header unset X-Pingback

Now edit the /etc/apache2/apache2.conf file and add or change the following lines

Timeout 120
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 10
HostnameLookups off
ProxyRequests Off
ProxyVia Off
#Only allow proxies from local network
<Proxy "*">
    Order Deny,Allow
    Deny from all
    Allow from 192.168.0
    #  Require ip 192.168.0
</Proxy>

Finally run the following commands to make sure that Apache is using your new settings

sudo a2enconf php8.0-fpm
sudo a2dissite 000-default.conf
sudo systemctl restart php8.0-fpm
sudo systemctl restart apache2

Download and install Nextcloud

Running the following set of commands will download the latest version of the Nextcloud compressed file and install it into your web directory

cd ~
wget https://download.nextcloud.com/server/releases/latest.zip
unzip latest.zip
sudo mkdir /var/www/nextcloud
sudo cp -r nextcloud /var/www
sudo chown -R www-data:www-data /var/www/nextcloud
sudo chmod -R 755 /var/www/nextcloud

Create the Apache virtual host file

Edit the /etc/apache2/sites-available/nextcloud.conf file and add the following content (making sure to make the changes necessary for your own installation)

<VirtualHost *:80>
  ServerAdmin email_address
  ServerName domain.com
  DocumentRoot /var/www/nextcloud
  Protocols h2 http/1.1
  DirectoryIndex index.php

  SetEnv TZ Europe/London
  AddDefaultCharset UTF-8
  DefaultLanguage en
  FileETag none

  #if using Cloudflare or other proxy then uncomment the following line
  #RemoteIPHeader CF-Connecting-IP

  ProxyRequests Off
  ProxyVia Off

  <Proxy "*">
     Require ip 192.168.0
  </Proxy>

  <Directory /var/www/nextcloud>
     Require all granted
     AllowOverride All
     Options -Indexes +FollowSymLinks +MultiViews
   </Directory>

   <FilesMatch "\.php$">
      SetHandler "proxy:unix:/run/php/php8.0-fpm.sock|fcgi://localhost"
   </FilesMatch>

   ErrorLog /var/log/apache2/nextcloud-error.log
   CustomLog /var/log/apache2/nextcloud-access.log combined
</VirtualHost>

Run the following two commands to activate your new virtual host

sudo a2ensite nextcloud.conf
sudo systemctl restart apache2

Install a TLS certificate

Make sure that your site has a certificate to help secure it by running the following set of commands

sudo apt install snapd
sudo snap install core; sudo snap refresh core
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
sudo certbot -d [domain] --apache

Update the Apache virtual host file

Now that you have a certificate for your Nextcloud installation you should update your Apache virtual host files to add some extra security. Do so by adding the following lines to your /etc/apache2/sites-available/nextcloud-le-ssl.conf file.

Header always set Strict-Transport-Security "max-age=31536000; includeSubdomains"
Header set X-XSS-Protection "1; mode=block"
Header set X-Content-Type-Options nosniff
Header set X-Frame-Options DENY
Header set Referrer-Policy: no-referrer-when-downgrade
Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
Header set X-Permitted-Cross-Domain-Policies "none"
###Header set Content-Security-Policy "default-src 'self';"

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Add the following lines just below the </VirtualHost> tag
  # intermediate configuration
  SSLProtocol             all -SSLv3 -TLSv1 -TLSv1.1
  SSLCipherSuite       ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
  SSLHonorCipherOrder     off
  SSLSessionTickets       off
  SSLUseStapling On
  SSLStaplingCache "shmcb:logs/ssl_stapling(32768)"

Finally run sudo systemctl restart apache2 to make Apache use your latest configuration.

Complete Nextcloud installation

Run the following three commands to set up a directory for your Nextcloud data then visit your domain in a browser.

sudo mkdir /var/www/ncdata
sudo chown -R www-data:www-data /var/www/ncdata
sudo chmod -R 755 /var/www/ncdata

When running through the installation script most of the answers to the questions should be evident. The database details are what you entered above and your data directory is /var/www/ncdata.

Once installed make sure that Apache can read the .htaccess file by running sudo chown www-data:www-data /var/www/nextcloud/.htaccessand then run sudo nano /var/www/nextcloud/config/config.php to finish setting up the Redis cache by adding the following line to the $CONFIG array

'htaccess.RewriteBase' => '/',

and the following lines to the end of the file

'memcache.distributed' => '\\OC\\Memcache\\Redis',
'memcache.local' => '\\OC\\Memcache\\Redis',
'redis' => 
  array (
   'host' => 'localhost',
   'port' => 6379,
 ),
'default_phone_region' => 'GB',

Now finish off this section by running the following commands

cd /var/www/nextcloud
sudo -u www-data php occ maintenance:update:htaccess
sudo systemctl restart redis.service
sudo crontab -u www-data -e
  Append the following line
    */5  *  *  *  * php -f /var/www/nextcloud/cron.php

The final steps

Login to your Nextcloud instance and change the background tabs to use cron. At this point it is also worth looking at which other apps you might want to use and installing them.

It is well worth looking through all the settings pages to make sure that Nextcloud is set up just the way you want it.