避免假设
一切正常,我可以读写文件
这表明文件权限本身和所有权允许当前使用。如果像你说的 apache 是作为 www-data 运行的,那就直接矛盾了:
根据请求的文件权限:-rw-r--r-- 1 daemon daemon 41638 Jan 19 08:59 FILE
这意味着该文件不可写入 www-data。
因为我试图以 www-data 用户(php 脚本)的身份删除文件,但文件的所有者是守护程序用户。
上述说法不正确 - 文件的所有权不影响谁可以删除它。
我不是在寻找任何 chmod 或 chown 解决方案,我更喜欢通过 Apache 或其他一些配置文件的解决方案。
在你有选择之前不排除解决方案怎么样?
删除文件使用目录权限,而不是文件权限
这很容易验证:
-> pwd
/tmp/so
-> whoami
www-data
-> ls -la
total 8
dr-xr-xr-x 2 www-data www-data 4096 Feb 18 14:34 .
drwxrwxrwt 8 root root 4096 Feb 18 14:36 ..
-rw-rw-r-- 1 www-data www-data 0 Feb 18 14:34 a-file
-> rm a-file
rm: cannot remove `a-file': Permission denied
请注意,文件夹 /tmp/so 没有写入权限 - 这是唯一重要的权限。这是另一个existing answer as a supportive reference。
因此,唯一的解决方案是确保尝试删除a-file 的用户具有对包含文件夹的写入权限,这意味着例如:
# assuming daemon is the owner
chmod 7x7 www/myapp/files
^ www-data is not the owner or in the group daemon - so world perms apply
或者
chown www-data:www-data www/myapp/files
chmod 7x7 www/myapp/files
^ daemon needs write permission to the folder too
或者
chown www-data:sharedgroup www/myapp/files
chmod 77x www/myapp/files
^ daemon now reads the group perm, www-data is the owner
(上传进程作为 daemon:sharedgroup 运行)
以上是需要运行的一次性命令;之后,无需修改任何文件或文件夹的权限以允许 www-data 和 daemon 操作 www/myapp/files 中的文件。