Running Apache + PHP as a different user

On my local system I started to run Apache under the same user account as my login account. The reason is to avoid permission issues during development. Often I use a CMS. After installing plugins or updating the system, these files belong to the Apache user. This can cause permission conflicts, if combined with a version control system. Running Apache as my normal user solves that problem for me.

Changing the Apache user is relatively easy. Just update the user in the configuration. I run openSUSE and Apache runs here as wwwrun. So your Apache user and configuration file may be different depending on your OS or distribution.

/etc/apache2/uid.conf


User yourusername
Group www

You have to change the owner of PHP's temporary files folder. Again the location may differ for you.


sudo chown -R yourusername.www /var/lib/php5

Also, you can delete the Apache user, because it is not needed any more.


sudo userdel wwwrun

Unfortunately, openSUSE changes the owner back to the default Apache user after an update. I couldn't find the location where this happens. So I turned to systemd to always set the correct user.

/usr/lib/systemd/system/apache2.service


[Unit]
Description=The Apache Webserver
Wants=network.target nss-lookup.target
After=network.target nss-lookup.target
Before=getty@tty1.service

[Service]
Type=notify
PrivateTmp=true
EnvironmentFile=/etc/sysconfig/apache2
ExecStart=/usr/sbin/start_apache2 -D SYSTEMD -DFOREGROUND -k start
ExecReload=/usr/sbin/start_apache2 -D SYSTEMD -DFOREGROUND -k graceful
ExecStop=/usr/sbin/start_apache2 -D SYSTEMD -DFOREGROUND -k graceful-stop
ExecStartPre=/usr/bin/chown -R yourusername.www /var/lib/php5

[Install]
WantedBy=multi-user.target

Restart Apache to load the new configuration


sudo systemctl daemon-reload
sudo systemctl restart apache2

To see if there were no errors, check the status:


sudo systemctl status apache2

On some systems you have to use systemctl restart apache2.service or service apache2 restart