1. Understand identity and ownership

id
whoami
getent passwd
getent group

Linux access decisions combine user ID, group membership and mode bits (or ACLs). A file has an owner and a group; permissions are evaluated for owner, group and others.

中文说明:不要为了省事把网站目录或应用目录全部改成 777。应明确哪个系统用户需要读取或写入。

2. Create a dedicated user

sudo adduser deploy
sudo usermod -aG www-data deploy
id deploy

This example creates a deployment account and adds it to the web-server group. Only do this if the account genuinely needs that group membership. The -aG flags append supplementary groups; omitting -a can replace existing supplementary groups.

3. Read permission bits

stat -c '%A %a %U:%G %n' /var/www
namei -l /var/www/html/index.html

Typical static website permissions are directories 755 and files 644 when the web server only needs read access. This is not universal: applications that upload files need a deliberately scoped writable directory.

4. Apply ownership and permissions carefully

sudo chown -R root:www-data /var/www/example
sudo find /var/www/example -type d -exec chmod 755 {} \;
sudo find /var/www/example -type f -exec chmod 644 {} \;
Review the target path before running recursive commands. A typo in chown -R or chmod -R can break system services or expose private files.

5. Use ACLs for exceptions

getfacl /var/www/example
sudo setfacl -m u:deploy:rwX /var/www/example
getfacl /var/www/example

ACLs can grant a specific account access without changing the primary owner/group model. Document non-obvious ACLs so future administrators understand them.

6. Audit sudo access

sudo -l -U deploy
groups deploy
getent group sudo

Grant administrative privileges only when required. Prefer narrowly scoped command access over unrestricted root access where practical.

Verification checklist

  • Confirm the intended owner and group.
  • Check every parent directory with namei -l.
  • Test access as the service account.
  • Avoid world-writable permissions unless there is a documented reason.
  • Review sudo and group membership regularly.

References & further reading

Commands are examples for a representative Ubuntu/Linux environment. Review paths, versions, access requirements and maintenance impact before applying them to production systems.