Skip to content
Workflows5 min readVerified Git 2.40+

How to Ignore a Directory in Git

Comprehensive guide to directory ignore rules: trailing slash behavior, root-relative folders, nested subdirectories, and keeping empty directories in Git.

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:

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

# Matches BOTH a directory named "build" AND a file named "build"
build
Best Practice

Always use a trailing slash when your intention is to exclude a directory. This clarifies intent and prevents Git from accidentally ignoring executable scripts or files named without extensions.

2. Root-Relative Directories vs Recursive Matching

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

gitignore
# Matches "logs/" anywhere in the repository: /logs/, /apps/web/logs/, etc.
logs/

# Anchored: Matches "logs/" ONLY at the repository root
/logs/

3. Nested Directories & Wildcards

When you need to ignore specific folders inside a parent structure without ignoring the parent, combine glob wildcards with directory paths:

gitignore
# Ignore any folder named "temp" inside any "build" directory
build/**/temp/

# Ignore all subdirectories inside packages except package files
packages/*/dist/

4. Keeping Empty Directories with .gitkeep

Git tracks files, not empty folders. If you need an empty directory structure committed (e.g., an empty uploads/ or logs/ folder), use the .gitkeep convention:

gitignore
# 1. Ignore everything inside uploads/
uploads/*

# 2. But whitelist the .gitkeep file inside it
!uploads/.gitkeep

5. Re-including Subfolders Safely

If a folder is excluded, you cannot simply whitelist a child folder with an exclamation mark. You must ignore folder contents and whitelist specific targets:

gitignore
# Ignore everything inside config/
config/*

# Whitelist production folder and its contents
!config/production/
!config/production/**

Frequently Asked Questions

Practical answers to common developer questions about .gitignore rules, caching, and repository configuration.

What is the difference between folder and folder/ in .gitignore?

'folder/' matches only directories. 'folder' without a slash matches both directories named folder and regular files named folder.

How do I commit an empty directory to Git?

Place an empty file named .gitkeep inside the directory, ignore all files inside with 'folder/*' and whitelist .gitkeep with '!folder/.gitkeep'.

How do I ignore the contents of a directory but keep the folder itself?

Use 'directory/*' instead of 'directory/'. This ignores everything inside without causing Git to skip the directory entirely.

← Read GuidesOpen in Full Generator