Lesson

Git .gitignore

10 min reading
Free Course

Git .gitignore: Keeping Secrets and Build Files Out of Git

A .gitignore file lists filename patterns that Git should leave untracked, preventing environment secrets (.env), dependency folders (node_modules/), OS junk (.DS_Store), and log files from polluting your repository. Keeping generated artifacts out of Git keeps repositories small and prevents leaking API credentials.

Essential .gitignore Pattern Syntax

Create a plain-text file named .gitignore at the root of your repository. Each line defines one matching pattern:

.env
.env.local
*.log
dist/
node_modules/
vendor/
!important-config.log
  • *.log matches any file ending in .log across every folder.
  • dist/ (trailing slash) matches only directories named dist.
  • !important-config.log negates a previous rule so that specific file remains tracked.
  • /config.local.php (leading slash) matches only in the repository root, not nested folders.

Untracking a File That Was Already Committed

.gitignore only applies to untracked files. If you already committed .env before adding it to .gitignore, Git continues tracking edits to .env until you remove it from the staging index while keeping the file on your disk:

git rm --cached .env
git commit -m "Stop tracking .env and enforce .gitignore"

Remember that .env still exists in earlier commits—if it held real passwords or keys, rotate those credentials immediately.

Global Personal .gitignore for Editor Files

Instead of adding .vscode/ or .DS_Store to every team repository's .gitignore, configure a personal global ignore file on your laptop:

git config --global core.excludesfile ~/.gitignore_global

Common .gitignore Mistakes

Putting node_modules without a trailing slash also ignores any file accidentally named node_modules. Always include the trailing / for directories, and test why a file is ignored anytime using git check-ignore -v <path>.

Frequently Asked Questions

Why does git status still show a file I just added to .gitignore?

That file was already tracked in an earlier commit. Run git rm --cached <file> and commit the removal so .gitignore takes effect from that point forward.

Should .gitignore itself be committed to the repository?

Yes. Commit your project .gitignore so every teammate and CI runner shares the exact same ignore rules automatically.

How do I see which rule in .gitignore is blocking a file?

Run git check-ignore -v path/to/file. Git prints the exact .gitignore file path and line number matching that file.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol
Git Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum