If you want the directories to still get created, you need to have something in them, so I make sure there is an index.html file in each of the EE image directories that says "Directory Access not allowed" (or similar). Then, for each of the directories you can add rules like the following (your paths may vary):
Since Git can currently only stage files and not empty directories, the only purely Git based solution is to do as you are now.
An alternative approach is to include a bash script in your repo that creates any required cache directories if the do not exist and (importantly) sets permissions on these directories (which often needs to be 755/777).
The other answers are going about this a slightly convoluted way. You don't need a special .gitignore in each folder, and that makes it hard for other developers to figure out what's going on (or you in a few months).
Just ignore the whole cache folder in your root .gitignore:
$ cd /path/to/root
$ echo "system/expressionengine/cache/" >> .gitignore
A possibly cleaner way would be to have it in your .gitignore at the root level of your repo...
... that way everything's centralized in that one .gitignore. However it's my preferred method to have multiple .gitignore files (like your example above), one in each "empty" directory ...
The github/gitignore repo is usually a good starting place for gitignore defaults, and I think it is in this case as well:
The path to some of your folders will obviously be different.
We use a single .gitignore file in the root directory, and we specifically list all subfolders. This way, the cache folder can contain the default index.html file, and will be indexed by git.
You probably got errors because EE couldn't find the cache folder. I'm new to git, and I have all my ignore rules in one file in the root and there I have this
Lately I have been using this as the default gitignore for non-EE projects and I was thinking of adapting it for EE. i'm open for suggestions.
#ignore everything apart from php, css, xml, htaccess, sql, js
I guess you know this, but you shouldn't set up your production sites like that. Ideally it should be:
You don't want any expressionengine files, addon files, or .git files to be accessible via webroot, or even set up some system to make them unavailable - the easiest and safest is just to keep ...
Personally, I wouldn't want my deployment method to dictate my placement of Git related files. I would rather my deployment process "clean" my environment and perhaps as a back-up, configure the web server to not serve Git related files. For example, here are some suggestions for Apache configurations in another question.