You can use ACLs to do this. For example:
$ ls -ld /var/www
drwxr-xr-x 2 apache www 4096 Aug 7 13:53 /var/www
$ sudo setfacl -dRm u:apache:rwX,g:www:rwX /var/www
$ ls -ld /var/www
drwxr-xr-x+ 2 apache www 4096 Aug 7 13:53 /var/www
$ getfacl /var/www
# file: var/www
# owner: apache
# group: www
user::rwx
group::r-x
other::r-x
default:user::rwx
default:user:apache:rwx
default:group::r-x
default:group:www:rwx
default:mask::rwx
default:other::r-x
When new files are created there by they will still be owned by your user, but there will also be an ACL set on it granting privileges to the apache user:
$ touch donkey
$ ls -l donkey
-rw-rw-r--+ 1 gene gene 0 Aug 7 13:57 donkey
$ getfacl donkey
# file: donkey
# owner: gene
# group: gene
user::rw-
user:apache:rwx #effective:rw-
group::rwx #effective:rw-
group:www:rwx #effective:rw-
mask::rw-
other::r--
An overview of the command:
setfacl -dRm u:apache:rwX,g:www:rwX /var/www
- The
-d
flag specifies the operations apply to the Default ACL.
- The
-R
flag sets operations to apply recursively
- The
-m
indicates it will be a modification operation
Then after that it's pretty straight forward
- u:USERNAME:permissions
- g:GROUPNAME:permissions
These entries must be separated by a comma.
The X
permission (note: it's uppercase) means it will only be applied to directories and not files.