Skip to content
Workflows & Directory Rules5 min readVerified Git 2.40+

How to Ignore a Directory in Git

Ignoring directories is the most common task in .gitignore files. Whether you want to ignore build outputs like dist/, dependency folders like node_modules/, or temporary caches, getting the trailing slash and root anchoring right is critical.

1. The Trailing Slash Rule: build/ vs build

In Git, appending a trailing forward slash (/) tells Git to check only directories and skip regular files with the same name:

# Matches only directories named "build/" (e.g. /build/, /src/build/)
build/

# Matches BOTH a directory named "build" AND a file named "build" (or "build.sh" if wildcarded)
build

Best practice: Always use a trailing slash when your intention is to exclude a directory.

2. Root-Relative Directories vs Recursive Matching

By default, a directory name without a leading slash matches at any depth in your project:

Recursive (No leading slash): temp/

Ignores temp/ in the root, but also ignores src/temp/, packages/web/temp/, etc.

Root-Relative (Leading slash): /temp/

Only ignores temp/ located directly in the root alongside .gitignore. Any subdirectory like src/temp/ will continue to be tracked normally.

3. Keeping Empty Directories in Git with .gitkeep

Git tracks files, not empty folders. If you have an uploads/ or logs/ folder that needs to exist in the repository structure but whose contents should be ignored, use this pattern:

# Ignore everything inside uploads/
uploads/*

# But keep the .gitkeep file so Git tracks the directory itself
!uploads/.gitkeep

4. What if the Directory is Already Committed?

Adding a directory to .gitignore after it was already committed does not delete it from Git history. You must tell Git to unstage the folder from its cache:

# Remove directory from Git index recursively without deleting local files
git rm -r --cached my-directory/

# Commit the removal
git commit -m "chore: untrack my-directory"

Need .gitignore Rules for Your Framework?

DotGitIgnore includes verified directory ignore patterns for Node.js (node_modules/), Python (.venv/), Java (target/), and 220+ more stacks.

Generate Custom .gitignore