The rsync command is the gold standard for backing up and synchronizing data across Linux servers. It is incredibly efficient because it only transfers the specific bytes of a file that have changed, rather than copying the entire file every time.
However, when you are backing up an entire home directory or a web server root, you rarely want to copy everything. You usually want to skip massive cache folders, temporary files, or hidden configuration directories. Fortunately, rsync provides a powerful set of exclusion rules that allow you to dictate exactly what gets left behind during a transfer.
The Basic Exclude Command
The simplest way to prevent rsync from copying a specific file or folder is to use the --exclude flag followed by the name of the item.
Imagine you want to backup your entire /var/www/website directory to a backup drive, but you want to skip the folder named cache.
rsync -avz --exclude 'cache' /var/www/website/ /mnt/backup/
When this command runs, rsync will copy everything inside the website folder except any file or directory named exactly “cache”.
Excluding by File Extension (Wildcards)
You can use standard Linux wildcards (asterisks) to exclude groups of files based on their extensions or naming patterns.
If you want to backup a project folder but ignore all the massive .mp4 video files and temporary .tmp files, you can chain multiple exclude flags together:
rsync -avz --exclude '*.mp4' --exclude '*.tmp' /home/user/project/ /mnt/backup/
Excluding Specific File Paths
The previous examples exclude files based on their name, regardless of where they are located. If you type --exclude 'cache', it will ignore /website/cache as well as /website/images/cache.
If you only want to exclude a specific folder at the root of your transfer but keep folders with the same name elsewhere, you must use a leading slash (/). This tells rsync to anchor the exclusion to the source directory.
rsync -avz --exclude '/cache' /var/www/website/ /mnt/backup/
This command skips the main cache folder but will successfully backup /var/www/website/plugin/cache.
Using an Exclude File for Complex Backups
If you are managing a complex server backup, your exclude list might be dozens of lines long. Typing --exclude twenty times in the terminal is impractical and prone to errors. Instead, you can write all your rules into a simple text file and tell rsync to read from it.
First, create a text file using nano or vim:
nano /home/user/backup-exclude.txt
Inside the file, list one rule per line. You do not need quotation marks here.
.cache/
*.mp4
*.iso
/Downloads/
temp_data.txt
Save and close the file. Now, run your rsync command and use the --exclude-from flag, pointing it to your text file:
rsync -avz --exclude-from='/home/user/backup-exclude.txt' /home/user/ /mnt/backup/
This is the cleanest, most professional way to manage automated cron job backups, allowing you to easily update your exclusion rules without ever touching the underlying bash script.