Apache file ownership and envvars

So, this will depend heavily on how you do your PHP.

There's two typical approaches to this with Apache, and each have different considerations to fix this issue with permissions.


Embedded php module in Apache

This is the simplest solution to get Apache to work with PHP. PHP runs within Apache, and runs as the Apache configured user.

sudo apt install libapache2-mod-php
sudo a2enmod php
sudo systemctl restart apache2.service

PHP FPM

PHP FPM is the other option - you would install the php-fpm package, but you'll also need extra work with Apache to make it work.

sudo apt install libapache2-mod-fcgid php-fpm

You then need to enable the FCGId module in Apache, as well as the alias and proxy_fcgi modules:

sudo a2enmod actions fcgid alias proxy_fcgi

For Ubuntu 20.04, PHP is 7.4, so you will need to add this to your server configuration wherever you're using php-fpm:

    <FilesMatch \.php$>
        # 2.4.10+ can proxy to unix socket
        SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost"
    </FilesMatch>

This must be within your <VirtualHost ...> blocks wherever you're using PHP.

You then must adjust /etc/php/7.4/fpm/pool.d/www.conf to make it use the user you intend to - look for the user = www-data line, and adjust this to the user you want. I would comment this line out and then put your user defined one underneath it, but that will change the user in use by php-fpm for it to read/write with.


Either of these approaches will fix your PHP user/group that it writes/creates files with - it just depends how you install PHP - Apache embedded module, or FPM.