Setting up Nextcloud with FreeIPA for my Linux-Based Enterprise
I’m trying to build a business around self-hosted and open source software. Is it finally the year of Linux in the enterprise? I’ve tried FreeIPA, worked through distributing my policy through RPM packages, and now I need a groupware solution for my business. I’m trying Nextcloud, integrated into my FreeIPA setup, with automatic login using Kerberos.
Contents⌗
- Video
- Basic Setup
- Basic Setup - Install Dependencies
- Basic Setup - Configure PHP
- Basic Setup - Configure Certbot
- Basic Setup - Configure Nginx
- Basic Setup - Install Nextcloud
- LDAP for FreeIPA
- LDAP - FreeIPA System Account Configuration
- LDAP - Nextcloud Server Setup
- LDAP - Nextcloud LDAP Backend
- Kerberos for FreeIPA
- Kerberos - Nextcloud SAML
- Kerberos - Keytab
- Kerberos - Fallback Page
- Kerberos - Nginx Config
Video⌗
Basic Setup⌗
I’m going to speedrun through a very basic Nextcloud initial setup - this gets us up and running, so we can then move on to the real integration with FreeIPA. I’m using Debian 13 (Trixie), along with the Nginx, PHP, Postgres, and Valeky versions it ships with. I’m using Nextcloud 35, which is currently the latest release, although their release scheme should really call this a beta.
Install + Confgure Dependencies⌗
# Install php and all modules, postgresql, valkey (redis), nginx
apt install nginx php-fpm php-cli php-pgsql php-gd php-curl php-mbstring php-xml php-zip php-intl php-bcmath php-gmp php-ldap php-apcu php-redis php-imagick postgresql valkey-server bzip2 unzip curl sudo certbot
# Create Postgres user + database (you probably want a better password, but it's localhost only)
sudo -u postgres psql <<'EOF'
CREATE USER nextcloud WITH PASSWORD 'CorrectHorseBatteryStaple';
CREATE DATABASE nextcloud OWNER nextcloud ENCODING 'UTF8' TEMPLATE template0;
EOF
# Stop nginx (we will start it once it's reconfigured)
systemctl stop nginx
Configure PHP⌗
Next up, we’re going to configure PHP. Drop this in /etc/php/8.4/fpm/conf.d/69-nextcloud.ini:
memory_limit = 512M
upload_max_filesize = 2G
post_max_size = 2G
max_execution_time = 3600
max_input_time = 3600
output_buffering = 0
opcache.enable = 1
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 10000
opcache.memory_consumption = 128
opcache.save_comments = 1
opcache.revalidate_freq = 60
apc.enabled = 1
apc.enable_cli = 1
And also /etc/php/8.4/cli/conf.d/69-nextcloud.ini:
apc.enable_cli = 1
Finally, a few more php configs:
# Update php www.conf, add these options
echo "clear_env = no" >> /etc/php/8.4/fpm/pool.d/www.conf
echo "env[PATH] = /usr/local/bin:/usr/bin:/bin" >> /etc/php/8.4/fpm/pool.d/www.conf
# And restart PHP
systemctl restart php8.4-fpm
Configure Certbot (optional)⌗
Certbot on Debian already comes with a systemd renewal timer, so we just need to request the initial certificate. Nginx is not yet running, so we need to do this using the ‘standalone’ method initially.
# Request certificates standalone (certbot hosts port 80 server, nginx shutdown)
certbot certonly --standalone -d cloud.example.com
# After you restart nginx, you can reconfigure certbot, so it renews automatically using webroot
#certbot reconfigure --cert-name cloud.example.com --authenticator webroot --webroot-path /var/www/nextcloud
Configure nginx⌗
This nginx config is copied almost verbatim from Nextcloud’s documentation - read the full description there. This file goes in /etc/nginx/sites-available/nextcloud.
# Nextcloud nginx configuration — root installation
# Version 2026-06-09
# With a few updates by apalrd
# PHP-FPM backend.
upstream php-handler {
# Debian uses a unix socket by default
server unix:/run/php/php8.4-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 {
listen 80;
listen [::]:80;
server_name cloud.example.com;
# Prevent nginx HTTP Server Detection
server_tokens off;
# Enforce HTTPS
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
listen 443 quic;
listen [::]:443 quic;
http2 on;
server_name cloud.example.com;
# Path to the root of your installation
root /var/www/nextcloud;
# Use Mozilla's guidelines for SSL/TLS settings
# https://mozilla.github.io/server-side-tls/ssl-config-generator/
ssl_certificate /etc/letsencrypt/live/cloud.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/cloud.example.com/privkey.pem;
# 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/.
# Max-age lowered for demo
add_header Strict-Transport-Security "max-age=3600" always;
# set max upload size and increase upload timeout:
client_max_body_size 512M;
client_body_timeout 300s;
fastcgi_buffers 64 4K;
# Proxy and client response timeouts
# Uncomment an increase these if facing timeout errors during large file uploads
#keepalive_timeout 60s;
#proxy_connect_timeout 60s;
#proxy_send_timeout 60s;
#proxy_read_timeout 60s;
#send_timeout 60s;
# 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;
# 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; }
# Hide metadata files which would otherwise be served as plain files and
# leak dependency information (composer.json, package.json, core/shipped.json).
location ~ ^/(?:composer\.(?:json|lock)|package(?:-lock)?\.json|core/shipped\.json)$ { return 404; }
# Pass PHP requests to PHP-FPM.
#
# Important: this block must appear above the static asset locations
# below. Those locations fall back to `/index.php$request_uri`; if
# they appear first, nginx can repeatedly rewrite to `/index.php`,
# causing an internal redirection loop.
location ~ \.php(?:$|/) {
# Rewrite most PHP requests to Nextcloud's front controller (`/index.php`).
#
# (Mirrors the rewrite exceptions in Nextcloud's Apache .htaccess.)
#
# Exceptions (not rewritten; must remain directly reachable):
# index.php, remote.php, public.php, cron.php, status.php
# ocs/v1.php, ocs/v2.php, ocs-provider/*
# core/ajax/update.php, updater/*
# */richdocumentscode(_arm64)?/proxy
#
# Other exceptions (e.g. /.well-known) are handled by dedicated
# location blocks elsewhere in this config.
#
# Caution: small edits to this regex can break routing or introduce
# rewrite loops.
rewrite ^/(?!index|remote|public|cron|status|ocs\/v[12]|ocs-provider\/.+|core\/ajax\/update|updater\/.+|.+\/richdocumentscode(_arm64)?\/proxy) /index.php$request_uri;
# Split `/file.php/path/info` into:
# - $fastcgi_script_name: `/file.php`
# - $fastcgi_path_info: `/path/info`
#
# This is required for entry-points such as `remote.php` and `public.php`,
# which route requests based on PATH_INFO.
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
set $path_info $fastcgi_path_info; # Save before try_files resets it
# Return 404 for nonexistent PHP scripts (avoids passing arbitrary
# paths to PHP-FPM, which is a known security risk).
try_files $fastcgi_script_name =404;
include fastcgi_params;
fastcgi_pass php-handler;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $path_info;
fastcgi_param HTTPS on; # Assumes TLS terminates here
fastcgi_param modHeadersAvailable true; # Avoid duplicate security headers
fastcgi_param front_controller_active true; # Enable pretty URLs
# Let nginx handle HTTP error responses from PHP-FPM (e.g. custom
# error pages). Disable for debugging if PHP errors are being hidden.
fastcgi_intercept_errors on;
# Required for uploads: PHP-FPM does not support chunked
# transfer encoding and needs a Content-Length header.
fastcgi_request_buffering on;
# Optional PHP-FPM timeout tuning (e.g. for 504 response timeouts).
# Increase these only if uploads or long-running PHP requests are
# timing out in your environment.
#fastcgi_read_timeout 60s;
#fastcgi_send_timeout 60s;
#fastcgi_connect_timeout 60s;
# Disable on-disk buffering of FastCGI responses (reduces disk I/O at
# the cost of holding responses in memory).
fastcgi_max_temp_file_size 0;
}
# Serve static files
location ~ \.(?:css|js|mjs|svg|gif|ico|jpg|png|webp|wasm|tflite|map|ogg|flac|mp4|webm)$ {
try_files $uri /index.php$request_uri;
# HSTS settings - ensure these match everywhere
add_header Strict-Transport-Security "max-age=3600" always;
# 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;
access_log off; # Optional: Don't log access to assets
}
location ~ \.(otf|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;
}
}
After creating the configuration, let’s disable the default nginx server and enable the nextcloud one we just created, then restart nginx:
cd /etc/nginx/sites-enabled
rm default
ln -s ../sites-available/nextcloud nextcloud
systemctl restart nginx
Install Nextcloud⌗
Nextcloud Download⌗
# One speedrun to getting nextcloud 35 downloaded
cd /tmp
curl -O https://download.nextcloud.com/server/releases/latest-35.tar.bz2
curl -O https://download.nextcloud.com/server/releases/latest-35.tar.bz2.sha256
sha256sum -c latest-35.tar.bz2.sha256
tar -xjf latest-35.tar.bz2 -C /var/www/
mkdir -p /srv/nextcloud
chown -R www-data:www-data /var/www/nextcloud /srv/nextcloud
chmod 750 /srv/nextcloud
Nextcloud Wizard⌗
Now, you can do the setup wizard for Nextcloud by visiting https://cloud.example.com. In this example, I’ve used the following parameters, but you’ll need to substitute your own:
DB User: nextcloud
DB Password: CorrectHorseBatteryStaple
DB Host: localhost:5432
Data Dir: /srv/nextcloud
Nextcloud Cron⌗
Nextcloud needs Cron to run periodically, so let’s setup a 5 minute job for background tasks:
#This will replace www-data's existing crontab
#They won't have one anyway, unless you are re-using this host for other things
echo "*/5 * * * * php -f /var/www/nextcloud/cron.php" | crontab -u www-data -
Nextcloud Cache⌗
Using APCu and Redis can speed up access. You can optionally enable one or both of these. I’ve already installed Valkey (Redis-compatible) earlier, so we will set that up by creating /var/www/nextcloud/config/cache.config.php:
<?php
$CONFIG = array (
'memcache.local' => '\OC\Memcache\APCu',
'memcache.distributed' => '\OC\Memcache\Redis',
'memcache.locking' => '\OC\Memcache\Redis',
'redis' => [
'host' => '[::1]',
'port' => 6379,
],
);
LDAP for FreeIPA⌗
This is a bit more complicated, so I’ve broken this up into sections.
FreeIPA system account configuration⌗
Next up, we need a system account in FreeIPA for Nextcloud to make LDAP connections. I created this on the IPA server:
ldapmodify -x -D "cn=Directory Manager" -W -H ldaps://your-ipa-server-here <<EOF
dn: uid=nextcloud,cn=sysaccounts,cn=etc,dc=apalrd,dc=fi
changetype: add
objectclass: account
objectclass: simplesecurityobject
uid: nextcloud
userPassword: CorrectHorseBatteryStaple
passwordExpirationTime: 20380119031407Z
nsIdleTimeout: 0
EOF
After that, we can create a user group in FreeIPA for who can log in to Nextcloud. I called mine ncusers.
Nextcloud Server Prep⌗
Before we start, we need to make sure that our Nextcloud server trusts FreeIPA. You can either domain join the Nextcloud server (which will automatically setup this trust), or if the server is not part of your infrastructure, you can manually add the FreeIPA root certificate (/etc/ipa/ca.crt on your ipa server) to /usr/local/share/ca-certificates and run update-ca-certificates.
Nextcloud LDAP Backend⌗
After that, we need to install the LDAP users and groups backend app in Nextcloud (you can do this by running php -f /var/www/nextcloud/occ app:enable user_ldap or from the web ui), and go to the LDAP tab on the admin page to configure it.
Nextcloud LDAP Server tab⌗
Here are the settings I used on the server tab:
Host: ldaps://your-ipa-server-here
Port: 636
User DN: uid=nextcloud,cn=sysaccounts,cn=etc,dc=apalrd,dc=fi
Password: CorrectHorseBatteryStaple
Base DN: dc=apalrd,dc=fi
Nextcloud LDAP Users tab⌗
In the Users tab, use ‘Edit LDAP Query’ and use this - it will check if the user is a member of the ncusers group and not locked.
(&(objectClass=posixaccount)(memberOf=cn=ncusers,cn=groups,cn=accounts,dc=apalrd,dc=fi)(!(nsAccountLock=TRUE)))
Nextcloud LDAP Login Attributes tab⌗
In this tab, check ‘LDAP/AD Username’ and ‘Edit LDAP Query’, with the following value, which just uses the uid field as the username.
(&(objectClass=posixaccount)(uid=%uid))
Nextcloud LDAP Groups Tab⌗
In this tab, check ‘Edit LDAP Query’ with the following value:
(objectClass=ipausergroup)
Nextcloud LDAP Advanced Tab⌗
Here, you can optionally configure a database replica for failover, if you have multiple IPA LDAP servers. Also, some custom settings in the Directory section:
User Display Name Field: displayName
User Base Tree: cn=users,cn=accounts,dc=apalrd,dc=fi
Group Display Name Field: cn
Base Group Tree: cn=groups,cn=accounts,dc=apalrd,dc=fi
Group-Member Association: Member (AD)
Nested Groups: true
And in the Special Attributes section:
Email Field: mail
Nextcloud LDAP Expert Tab⌗
Internal Username: uid
Kerberos for FreeIPA⌗
Note: This requires LDAP to already be configured! We need LDAP for all of the user’s data / group membership / .., Kerberos is only providing Authentication, not Authorization.
Kerberos Enable SAML in Nextcloud⌗
Start by installing the “SSO & SAML Authentication” app in Nextcloud (via php -f /var/www/nextcloud/occ app:enable user_saml or the web UI).
Next, go to the configuration tab for SSO & SAML Authentication. Select “Use environment variable”, then set the following settings:
Only allow authentication if an account exists on some other backend (e.g. LDAP): true
Allow the use of multiple user back-ends (e.g. LDAP): true
Attribute to map the UID to: REMOTE_USER
Optional display name for the identity provider: Kerberos
Kerberos Keytab⌗
We need a service keytab for the site. My server was not domain joined, so here’s the process I used:
# On FreeIPA server
# Create host
ipa host-add cloud.apalrd.net --force
# Create service running on host
ipa service-add HTTP/cloud.apalrd.net
# Get keytab and put it in /tmp
ipa-getkeytab -s your-ipa-server-here -p HTTP/cloud.apalrd.net -k /tmp/http.keytab
# Export using base64, so we can copy/paste it to the Nextcloud server
base64 /tmp/http.keytab
# Delete it
rm /tmp/http.keytab
# On Nextcloud server
# Get the keytab, put it in nginx location
echo "Your-Base64-String-Here" | base64 -d - > /etc/nginx/http.keytab
chown www-data:www-data /etc/nginx/http.keytab
chmod 400 /etc/nginx/http.keytab
Kerberos Fallback Page⌗
Due to oddities in how SPNEGO / GSSAPI Kerberos authentication works, the web server must send a 401 Unauthorized to the browser. For browsers which do support Kerberos, they will reply with the Kerberos credentials and log in normally. For everyone else, they get stuck on the 401 page. To allow these people to login, write a plain HTML page which will redirect them to the login screen.
I put the file in /var/www/html/fallback.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="refresh" content="0; url=/login?direct=1">
<title>Redirecting…</title>
</head>
<body>
<p>No Kerberos ticket found. <a href="/login?direct=1">Continue to the login page</a>.</p>
<script>location.replace("/login?direct=1");</script>
</body>
</html>
Kerberos SPNEGO for Nginx⌗
We also need to add SPNEGO support to Nginx, so let’s install that module. Nginx will load it automatically on Debian.
apt install -y libnginx-mod-http-auth-spnego
Next, we need to configure Nginx to use SPNEGO authentication only for the login page and nothing else (Nginx will then cache sessions as it usually does for the rest of the pages). Add this to the /etc/nginx/sites-available/nextcloud we created earlier. Insert this on line number 155 (in my example config) - right before # Pass PHP requests to PHP-FPM.
# Kerberos-protected SSO entry point only
location ~ ^/(?:index\.php/)?apps/user_saml/saml/login {
auth_gss on;
auth_gss_keytab /etc/nginx/http.keytab;
auth_gss_service_name HTTP/cloud.apalrd.net;
auth_gss_realm APALRD.FI;
auth_gss_force_realm on; # strip realm so REMOTE_USER = alice
auth_gss_allow_basic_fallback off; # no password prompt popup if no ticket
# No usable ticket -> send fallback page
error_page 401 /fallback.html;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_param PATH_INFO /apps/user_saml/saml/login;
fastcgi_param REMOTE_USER $remote_user;
fastcgi_param HTTP_AUTHORIZATION "";
fastcgi_param PHP_AUTH_USER "";
fastcgi_param PHP_AUTH_PW "";
fastcgi_param front_controller_active true;
fastcgi_param modHeadersAvailable true;
fastcgi_intercept_errors on;
fastcgi_pass php-handler;
}
location = /fallback.html {
internal;
root /var/www/html;
}
And finally restart nginx: systemctl restart nginx
Now it should all work, hopefully!