After trying some configurations, I came across with the solution. Having my repo with:
# tree -a
.
├── .git/*
├── .gitignore
├── a
│ └── should-be-taken.txt
├── b
│ └── should-be-ignored.txt
└── recursive
├── folder
│ └── should-be-taken.txt
└── no.txt
I got a solution with:
# cat .gitignore
*
!/a
!/a/**
!/recursive
!/recursive/folder
!/recursive/folder/**
!.gitignore
The key is to explicitly negate the whole folder path you want to not be ignored within your .gitignore file. And then ** matches everything inside, cf Git documentation:
A trailing "/**" matches everything inside. For example, "abc/**" matches all files inside directory "abc", relative to the location of the .gitignore file, with infinite depth.
EDIT: Even though my solution still works, there is another way shown in the gitignore Documentation Examples:
Example to exclude everything except a specific directory foo/bar (note the /* - without the slash, the wildcard would also exclude everything within foo/bar):
# exclude everything except directory foo/bar
/*
!/foo
/foo/*
!/foo/bar