How to ignore nested files in .gitignore?

Sometimes, especially when you use submodules or subpackages in your project, you will need to ignore locally generated files on them. The default .gitignore wildcard expression like *.txt should help:

bartosz:~$ cd /tmp/
bartosz:/tmp$ mkdir test_gitignore_nested
bartosz:/tmp$ cd test_gitignore_nested/
bartosz:/tmp/test_gitignore_nested$ git init
Initialized empty Git repository in /tmp/test_gitignore_nested/.git/
bartosz:/tmp/test_gitignore_nested$ echo "*.txt" >> .gitignore
bartosz:/tmp/test_gitignore_nested$ git add .gitignore
bartosz:/tmp/test_gitignore_nested$ git commit .gitignore -m "add .gitignore"
[master (root-commit) 054a172] add .gitignore
 1 file changed, 1 insertion(+)
 create mode 100644 .gitignore

And now I'll create some .txt files to see if the filter works:

bartosz:/tmp/test_gitignore_nested$ echo "test1" >> file.txt
bartosz:/tmp/test_gitignore_nested$ mkdir subdir/
bartosz:/tmp/test_gitignore_nested$ echo "test2" >> subdir/file2.txt
bartosz:/tmp/test_gitignore_nested$ git status
On branch master
nothing to commit, working directory clean

bartosz:/tmp/test_gitignore_nested$ mkdir subdir/subdir2
bartosz:/tmp/test_gitignore_nested$ echo "test2" >> subdir/subdir2/file2.txt
bartosz:/tmp/test_gitignore_nested$ git status
On branch master
nothing to commit, working directory clean

And as expected, if I add a not .txt file, it will be listed as untracked one:

bartosz:/tmp/test_gitignore_nested$ echo "test1" >> file.tmp
bartosz:/tmp/test_gitignore_nested$ git status
On branch master
Untracked files:
  (use "git add ..." to include in what will be committed)

    file.tmp

nothing added to commit but untracked files present (use "git add" to track)