.gitignore exclude files in directory but not certain directories

Solution 1:

Git doesn't track folders, only files, so if you ignore everything in a folder, Git won't have anything to track. You can add a .gitignore file to each directory (application/cache, application/cache/folder, application/cache/folder/onemorefolder/) with the following contents:

*
!.gitignore

Then, you can add those directories, and only the .gitignore file in each directory will get added -- but this means the directories will now be tracked (i.e., created when cloning).

Solution 2:

Git doesn't track empty directories. Just add some empty placeholder files in the folders you want to be committed.

touch application/cache/.keep
git add -f application/cache/.keep

Do this also with each "empty" folders. Later you can ignore these files, they really only exists to make sure that git creates those directories on clone. The entries in .gitignore keeps others files within the folders from being tracked (unless you force it with git add -f ;)).