Solution 1
I refer to Is there a safe and reliable way to move data directory out of web root? - #17 by robertb 2,5 тыс. where the steps are given and list/complete them here with commands where Apache webserver and MySQL/MariaDB database is assumed. Instead of prefixing all (non-www-data) commands with sudo, you could also start an interactive root session:
sudo -s
For simplicity, we store all relevant paths into variables to be used later. Replace those placeholder paths to match your setup.
ncdir='/path/to/nextcloud'
olddata='/old/path/to/data'
newdata='/new/path/to/data'
Put Nextcloud into maintenance mode
sudo -u www-data php "$ncdir/occ" maintenance:mode --on
Copy Nextcloud data to new location. The below command copies the whole directory, including owner and modes, so there is no need to pre-create the new directory, change ownership or permissions.
sudo cp -a "$olddata/." "$newdata"
Update the data dir in config.php to
'datadirectory' => '/new/path/to/data',. The sed command below should do it, but at best verify this afterwards, or edit the file manually.
sudo sed -i "s|$olddata|$newdata|" "$ncdir/config/config.php"
Create a database dump/backup. Depending on the root user’s database authentication method, you might need to add the -p option (mysqldump -A -p ...) to get a password prompt. Replace /path/to/backup with any directory, suitable to keep a backup of your database.
sudo mysqldump -A > /path/to/backup/dump.sql
Adjust oc_storages database table to reflect the new data folder location. We store the required database name and credentials, obtained from the config.php, into variables, to avoid typos. You might want to verify that those were obtained correctly, but be careful to print such sensitive information to the console, when others may watch, and exit the shell session afterwards.
dbname=$(sudo awk -F\' "/'dbname'/{print \$4;exit}" "$ncdir/config/config.php")
dbuser=$(sudo awk -F\' "/'dbuser'/{print \$4;exit}" "$ncdir/config/config.php")
dbpass=$(sudo awk -F\' "/'dbpassword'/{print \$4;exit}" "$ncdir/config/config.php")
#echo "$dbname $dbuser $dbpass"
mysql -u"$dbuser" -p"$dbpass" -e "update $dbname.oc_storages set id='local::$newdata/' where id='local::$olddata/';"
unset -v dbname dbuser dbpass
Disable maintenance mode
sudo -u www-data php "$ncdir/occ" maintenance:mode --off
After that, carefully test Nextcloud, the files inside web ui, shares, tags, comments etc. If everything is working fine and Nextcloud indeed handles the files on the new location, you could remove the backups:
sudo rm -R "$olddata"
rm /path/to/backup/dump.sql
or just keep them as regular backups ;).