.gitignore: how to write it properly
The .gitignore file tells Git which files to ignore. Learn the syntax rules, see templates for popular languages, and fix common mistakes.
What is .gitignore and why it matters
A .gitignore file tells Git which files and directories to exclude from version control. It sits at the root of your repository and applies rules to everything below it.
Without a .gitignore, Git would track everything: dependencies, build artifacts, environment secrets, OS files. This bloats your repository, slows down clones, and can leak sensitive data like API keys.
Every project should have a .gitignore file from the very first commit. It's one of the first things to set up after git init.
Files you should always ignore
node_modules/Dependencies (reinstalled via npm install)
.envAPI keys, secrets, database credentials
dist/ / build/Compiled output (regenerated on build)
.DS_StoremacOS system files with no project value
.gitignore syntax rules
The .gitignore file uses simple pattern matching. Here are the rules you need to know.
# Comments
Lines starting with # are comments. Use them to document why a rule exists.
# Ignore build output* Wildcard
Matches any number of characters (except /). Use ** to match across directories.
*.log # All .log files
**/*.tmp # All .tmp files in any subfolder/ Directory separator
A trailing slash means "directories only". A leading slash anchors the pattern to the repo root.
build/ # Ignore any directory named build
/build/ # Ignore build/ only at the repo root! Negation
Prefix with ! to re-include a file that was previously ignored. Order matters.
logs/ # Ignore the logs folder
!logs/.gitkeep # But keep this placeholder fileIn practice in the terminal
Create a .gitignore and fix files that are already tracked.
Create a .gitignore
Fix already-tracked files
Common .gitignore templates
Node.js
node_modules/
dist/
.env
.env.local
npm-debug.log*
.next/Python
__pycache__/
*.py[cod]
.venv/
.env
*.egg-info/
dist/Java
*.class
target/
.gradle/
build/
.idea/
*.jarGlobal .gitignore for your machine
Some files are personal to your environment and should never be committed in any project. Set up a global .gitignore to handle them once for all repositories.
What belongs in global
OS files (.DS_Store, Thumbs.db), editor configs (.vscode/, .idea/, *.swp), and any personal tooling files that aren't specific to a project.
What belongs in project .gitignore
Dependencies (node_modules/, .venv/), build output (dist/, target/), environment files (.env), and anything specific to the project's tech stack.
Part of the Git Basics guide
GitQuest is created by Anaïs (nouvelle fenêtre), web developer and head of education, specializing in tech training and digital accessibility.
Questions about .gitignore
Ready to set up your Git project properly?
GitQuest teaches you Git fundamentals step by step with interactive exercises in a safe terminal.
Start learning Git