Linux 的目录权限与文件权限的区别

文章目录

    问题

    帮朋友搭建一个 wordpress 站点,偷懒的在 root 帐号根目录下部署了。出现了神奇的报错

    stat() "/root/wordpress/" failed (13: Permission denied)
    stat() "/root/wordpress/" failed (13: Permission denied)
    stat() "/root/wordpress/index.php" failed (13: Permission denied)
    "/root/wordpress/index.php" is forbidden (13: Permission denied)
    

    页面上显示 404。这就非常诡异了,日志中显示权限有问题。即使我将 /root/wordpress/ 整个目录及子目录、文件都设置成 777 权限,也不行。还是报权限错误!

    万能的 777 都不行,还能怎么办?

    救赎

    Google 到了一个答案

    https://serverfault.com/questions/170192/nginx-php-fpm-permission-denied-error-13-in-nginx-log-configuration-mista/170263#170263

    You need to ensure you have +x on all of the directories in the path leading to the site’s root - so /home, /home/noisepages and /home/noisepages/www

    也就是说,需要将路径中的每一个目录都加上执行权限。果然,

    chmod +x /root
    

    之后,一切都正常了。。。

    然而,我完全不明白这是在干啥?

    为什么,父级目录的权限会影响到子目录的访问。

    冷静一下

    For a directory, execute permission allows a user to access, or traverse, into (i.e. cd) and access metadata about files in the directory (the information that is listed in an ls -l).

    stat 函数,是通过文件名获取到对应的文件信息。(类似,ls -l)

    这样想,如果为了安全,我将一个用户根目录针对另一个用户去掉了执行权限。那么理论上,其子目录的信息,都禁止其访问。除非他能通过 sudo cd 进去。

    那么,上面的问题就很好理解了。想通过文件/目录的绝对路径调用 stat 函数,获得文件信息,逻辑上是不能被允许的。那么报错就符合逻辑了。

    The way you access a file matters. For example, if you have execute permissions on /foo/bar but not on /foo, but your current directory is /foo/bar, you can access files in /foo/bar through a relative path but not through an absolute path. You can’t change to /foo/bar in this scenario; a more privileged process has presumably done cd /foo/bar before going unprivileged. If a file has multiple hard links, the path you use to access it determines your access constraints.

    下次如何快速定位问题

    如果想快速查看绝对路径中的每一个目录的权限及所有者,可以使用 namei 命令

    $ namei -mo ~/test/wordpress
    f: /home/zhongwei/test/wordpress
     drwxr-xr-x root     root     /
     drwxr-xr-x root     root     home
     drwx------ zhongwei zhongwei zhongwei
     drwxr-xr-x zhongwei zhongwei test
     drwxr-xr-x zhongwei zhongwei wordpress
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式