How To Install and Configure Nextcloud with Nginx, PostgreSQL and Redis on Ubuntu 18.04

How To Install and Configure Nextcloud with Nginx, PostgreSQL and Redis on Ubuntu 18.04

Prerequisites

  • Ubuntu 18.04

  • Root privileges

What we will do

  1. Install and configure Nginx Web server

  2. Install and Configure PHP7.4-FPM Install and

  3. Configure PostgreSQL Server

  4. Generate SSL Letsencrypt

  5. Download Nextcloud 16

  6. UFW Configuration

  7. Install Redis

  8. Nextcloud Post-Installation

 

 

1 - Install Nginx Web server

 

Generate SSL Letsencrypt

apt update
apt install nginx -y

Now go to the /etc/nginx/sites-available directory and create a new virtual host file nextcloud.

cd /etc/nginx/sites-available/
nano nextcloud

Paste the following nextcloud virtual host configuration and make sure to change example.com with your domain.

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

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    # enforce https
    return 301 https://$server_name:443$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com;

    # Use Mozilla's guidelines for SSL/TLS settings
    # https://mozilla.github.io/server-side-tls/ssl-config-generator/
    # NOTE: some settings below might be redundant
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this
    # topic first.
    #add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
    #
    # 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 X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;
    add_header Referrer-Policy no-referrer;

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

    # Path to the root of your installation
    root /var/www/nextcloud;

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

    # The following 2 rules are only needed for the user_webfinger app.
    # Uncomment it if you're planning to use this app.
    #rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
    #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json last;

    # The following rule is only needed for the Social app.
    # Uncomment it if you're planning to use this app.
    #rewrite ^/.well-known/webfinger /public.php?service=webfinger last;

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

    # set max upload size
    client_max_body_size 512M;
    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 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;

    # Uncomment if your server is build with the ngx_pagespeed module
    # This module is currently not supported.
    #pagespeed off;

    location / {
        rewrite ^ /index.php$request_uri;
    }

    location ~ ^\/(?:build|tests|config|lib|3rdparty|templates|data)\/ {
        deny all;
    }
    location ~ ^\/(?:\.|autotest|occ|issue|indie|db_|console) {
        deny all;
    }

    location ~ 
        ^\/(?:index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]- 
        provider\/.+)\.php(?:$|\/) {
        fastcgi_split_path_info ^(.+?\.php)(\/.*|)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param HTTPS on;
        # Avoid sending the security headers twice
        fastcgi_param modHeadersAvailable true;
        # Enable pretty urls
        fastcgi_param front_controller_active true;
        fastcgi_pass php-handler;
        fastcgi_intercept_errors on;
        fastcgi_request_buffering off;
    }

    location ~ ^\/(?:updater|oc[ms]-provider)(?:$|\/) {
        try_files $uri/ =404;
        index index.php;
    }

    # Adding the cache control header for js, css and map files
    # Make sure it is BELOW the PHP block
location ~ \.(?:css|js|woff2?|svg|gif|map)$ {
        try_files $uri /index.php$request_uri;
        add_header Cache-Control "public, max-age=15778463";
        # Add headers to serve security related headers (It is intended to
        # have those duplicated to the ones above)
        # Before enabling Strict-Transport-Security headers please read into
        # this topic first.
        #add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
        #
        # 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 X-Content-Type-Options nosniff;
        add_header X-XSS-Protection "1; mode=block";
        add_header X-Robots-Tag none;
        add_header X-Download-Options noopen;
        add_header X-Permitted-Cross-Domain-Policies none;
        add_header Referrer-Policy no-referrer;

        # Optional: Don't log access to assets
        access_log off;
    }

    location ~ \.(?:png|html|ttf|ico|jpg|jpeg)$ {
        try_files $uri /index.php$request_uri;
        # Optional: Don't log access to other assets
        access_log off;
    }
}

Enable the virtual host and test Nginx

ln -s /etc/nginx/sites-available/nextcloud /etc/nginx/sites-enabled/
systemctl start nginx
systemctl enable nginx
netstat -plntu

 

2 - Install and Configure PHP7.4-FPM

Install the 'software-properties-common' package and add the 'ondrej PHP' PPA repository

apt install software-properties-common -y
add-apt-repository ppa:ondrej/php -y

Install PHP dependencies

apt install php7.4-fpm php7.4-gd php7.4-pgsql php7.4-curl php7.4-xml php7.4-zip php7.4-intl php7.4-mbstring php7.4-json php7.4-bz2 php7.4-ldap php-apcu imagemagick php-imagick php-smbclient php-redis -y

Go to the '/etc/php/7.4' directory 

cd /etc/php/7.4/

Edit fpm/php.ini using nano.

nano fpm/php.ini

Ctrl + w to search in nano. Uncomment ‘date.timezone’ and ‘cgi.fix_pathinfo’ and change their values.

date.timezone = America/New_York
cgi.fix_pathinfo=0

I suggest to cange even these settings. Note that this is optional.

memory_limit = 512M
upload_max_filesize = 200M
max_execution_time = 360
post_max_size = 200M

Edit cli/php-cli

nano cli/php.ini

date.timezone = America/New_York
cgi.fix_pathinfo=0

Next, edit the php-fpm pool configuration www.conf.

nano fpm/pool.d/www.conf

Uncomment these lines.

env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp

Restart the PHP7.4-FPM service and enable it to launch every time on system boot.

systemctl restart php7.4-fpm
systemctl enable php7.4-fpm

Now check it using the netstat command.

netstat -pl | grep php

You can see that php-fpm is now running under the sock file /run/php/php7.4-fpm.sock.

 

3 - Install and Configure PostgreSQL Server

wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

add-apt-repository "deb http://apt.postgresql.org/pub/repos/apt/ bionic-pgdg main"

Install Postgres

apt install postgresql-11 -y

Log into an interactive Postgres session by typing:

sudo -u postgres psql

First, create a database for your project.

CREATE DATABASE nextcloud;

Next, create a database user for our project. Make sure to select a secure password.

CREATE USER myuser WITH PASSWORD 'password';

Now, we can give our new user access to administer our new database.

GRANT ALL PRIVILEGES ON DATABASE nextcloud TO myuser;

When you are finished, exit out of the PostgreSQL prompt by typing.

\q

Restart the relevant services.

systemctl restart postgresql && systemctl restart php7.4-fpm

4 - Generate SSL Letsencrypt

Install letsencrypt.

apt install letsencrypt -y

 After the installation is complete, stop the nginx service.

systemctl stop nginx

Next, we will generate the SSL certificate for your domain name using the cerbot command line. Make sure to change the domain.

certbot certonly --standalone -d example.com

Restart Nginx and Php

systemctl restart nginx
systemctl restart php7.4-fpm

 

5 - Download Nextcloud

Make sure the unzip package is installed on the system. If you don't have the package, install it using the apt command below.

apt install wget unzip zip -y
cd /var/www/
wget https://download.nextcloud.com/server/releases/latest.zip
 

Extract the zip file and you will get a nextcloud named directory, then create a new data named directory.

unzip latest.zip
mkdir -p nextcloud/data/

Now change the owner of nextcloud directory to the www-data user and group.

chown -R www-data:www-data /var/www/nextcloud/

 

6 - Configure UFW

ufw enable

Type 'y' and press Enter to start and enable the UFW firewall.

Now add new SSH, HTTP and HTTPS to the UFW firewall list.

ufw allow ssh
 
ufw allow http
ufw allow https

Check the allowed list port on the UFW firewall using the command below.

ufw status

 

7- Install Redis

Install Redis Server

apt install redis-server -y

Add the following lines to config.php

nano /var/www/nextcloud/config/config.php

'memcache.local' => '\\OC\\Memcache\\Redis',
  'filelocking.enabled' => 'true',
  'memcache.distributed' => '\\OC\\Memcache\\Redis',
  'memcache.locking' => '\\OC\\Memcache\\Redis',
  'redis' => array (
    'host' => 'localhost',
    'port' => 6379,
    'timeout' => 0,
    'dbindex' => 0,
  ),

Restart php7.4-fpm

systemctl restart php7.4-fpm

 

8 - Nextcloud Post-Installation

 

Open your web browser and type the nextcloud URL address. Create a nextcloud admin.

 

Type the database info that we've created in step 3