All files on /var/www/ change ownership to www-data. Can it be avoided?

I have different files with different owners, starting from the /var/www/* directory.

Files in /var/www/ need to be set to the user you use apache with. Otherwise you can run into permission issues and a website with potential security issues.

www-data was the default user for apache (v1). Nowadays apache (v2) uses apache as user and group. See your apache config on what user you use.

To change:

sudo vi /etc/apache2/apache2.conf

find the 2 lines (assuming your www-data as now set):

user www-data
group www-data

If you only want to change it to the user and group you use you can reset your data with this command (After changing user or group you also need to do this):

sudo chown --recursive {user}:{group} /var/www/

change {user} and {group} to what is in the configuration file and restart apache

sudo systemctl restart apache2 

Generic other pointers:

Permissions on files and directories should be at the most this:

sudo chmod 755 /var/    
sudo chmod 755 /var/www/
sudo find /var/www/ -type d -exec chmod 755 {} \;
sudo find /var/www/ -type f -exec chmod 644 {} \;    ]
  • "0" means nothing; "7" is read, write, and execute; "6" is read, write. The "d" means directories, the "f" means files.
  • Don't put executable files in /var/www/. Use a dedicated directory (apache has a cgi-bin option for this).
  • If possible set "others" to "0".
  • If possible set "group" to "0" as well; group is only needed if there are 2 or more users altering files on the server
  • If setting one of them to "0" and it yields permissions errors you have a mistake in a settings file for that specific software and should fix that setting instead of altering permissions.