What is the immutable flag?
Normal file permissions say who can read or write a file. But the owner of a file can still delete it. The immutable flag is a stronger lock. When it is on, no one can delete, rename or edit the file. Not even the root user can, until the flag is removed. It is like putting an item in a glass case.
The command is chattr, which means "change attribute". It works on Linux file systems such as ext4 and XFS.
Warning
A locked file cannot be updated. If an app needs to write to that file, it will stop working. Do not lock log files, cache files or anything that changes. Back up the file first.
Steps to lock a file
- Log in to your server over SSH as root.
- Check the file exists.
ls -l /home/username/domains/example.com/public_html/index.php
Replace the path with your real file. This shows the file and its owner.
- Lock the file.
chattr +i /home/username/domains/example.com/public_html/index.php
The +i adds the immutable flag.
- Check the flag is set.
lsattr /home/username/domains/example.com/public_html/index.php
You should see an i in the first column.
- Try to delete the file as the user, or from the DirectAdmin File Manager. It should say the operation is not permitted.
Lock a whole folder
Use chattr -R +i foldername. The -R makes it work on everything inside. The folder then cannot get new files either.
Steps to unlock
- Log in as root.
- Run the command below.
chattr -i /home/username/domains/example.com/public_html/index.php
The -i removes the lock. You can now edit or delete the file.
Quick recap
- Use chattr +i to lock a file so it cannot be deleted or changed.
- Use lsattr to see the lock and chattr -i to remove it.
- Do not lock files that apps need to write to.
- Only root can set or remove the flag.