Git Ignore (.gitignore)

A .gitignore file tells Git which files and folders it should not track. Use it for anything generated, private or machine-specific: dependency folders, build output, logs, secrets and editor settings.

Creating a .gitignore File

Create a plain text file named .gitignore in the root of your repository and commit it, so everyone on the team ignores the same files.

# Dependencies
node_modules/
vendor/

# Build output
dist/
build/

# Environment and secrets
.env
.env.*
!.env.example

# Logs and OS files
*.log
.DS_Store
Thumbs.db

# Editors
.vscode/
.idea/
$ git status
(node_modules, dist and .env no longer appear)

Pattern Syntax

  • # starts a comment; blank lines are ignored.
  • *.log — any file ending in .log, in any folder.
  • dist/ — a trailing slash matches folders only.
  • /config.json — a leading slash matches only in the root folder.
  • docs/**/*.pdf — ** matches any number of folders.
  • !important.log — ! re-includes a file excluded by an earlier pattern.

Ignoring Files You Already Committed

.gitignore only affects untracked files. If a file is already in the repository, remove it from the index (not from disk) and commit.

git rm --cached .env
git rm -r --cached node_modules
git commit -m "Stop tracking .env and node_modules"
rm '.env'
[main 7c8d9e0] Stop tracking .env and node_modules

Important: if a secret like an API key was committed, it is still in the history. Rotate (change) the secret immediately.

Checking Why a File Is Ignored

This shows which file and line caused the match, which is handy when a file is unexpectedly ignored.

git check-ignore -v debug.log
.gitignore:16:*.log	debug.log

Global and Local Ignores

For files only your machine creates, such as OS or editor files, you can set a personal global ignore file with git config --global core.excludesFile ~/.gitignore_global. For per-repository rules you do not want to share, use .git/info/exclude. Templates for most languages are available at github.com/github/gitignore.

Frequently asked questions

Why is my .gitignore not working?

The file is probably already tracked. Run git rm --cached <file> (add -r for folders) and commit; after that the ignore rule takes effect.

Should I commit .gitignore?

Yes. Committing it makes the whole team ignore the same generated and secret files.

Should node_modules be in .gitignore?

Yes. It is large and can be recreated with npm install from package.json and package-lock.json.