Gitignore and keeping secrets out of Git
A .gitignore file lists patterns Git should not track, and secrets such as .env files belong there, because anything committed stays in history even after you delete it.
- Updated Nov 27, 2026
- Markdown
Ignore files with .gitignore, untrack files already committed, keep config in .env.example, and respond correctly when a secret leaks.
- A Git repository with a few files
Put files that must not be shared into .gitignore, and keep real secrets in an .env file that is ignored, with a .env.example committed beside it. If a secret does get committed, rotate it first: change the password or revoke the token, because deleting it from a later commit leaves it in history. Cleaning history is a second, optional step.
How it works#
Git tracks every file you git add. A .gitignore file in the repository root lists patterns of files Git should leave alone, and each line is one pattern. Git skips matching untracked files, so they stay out of git status and out of git add .. It does nothing for a file that was already committed, which is the most common surprise.
Why care? A repository is a permanent record. Every commit is stored in full, and clones copy all of it. A password committed once is readable by anyone with the repository, in any old commit, until you rotate it. Secrets and build output both belong outside Git. For how apps read configuration instead, see environment variables and secrets.
Step 1: Write a .gitignore#
Create .gitignore at the top of the repository and commit it, so everyone shares the rules:
# secrets and local config
.env
*.pem
*.key
# dependencies and build output
node_modules/
dist/
build/
# logs and editor files
*.log
.DS_Store
.vscode/Pattern rules:
*matches any characters within one folder level,**/matches across folders.- A trailing
/matches directories only (dist/). - A leading
/anchors to the repository root (/config.local). !re-includes a file that an earlier pattern excluded (!.env.example).#starts a comment.
You can also keep personal ignores for your own machine in .git/info/exclude, or a global file set with git config --global core.excludesFile ~/.gitignore_global.
Step 2: Check what a rule does#
git check-ignore -v .envThe output is the file, the line number and the pattern that matched, for example .gitignore:2:.env .env. No output means the path is not ignored. List what Git currently ignores with git status --ignored.
Step 3: Stop tracking a file you already committed#
Adding a pattern is not enough for tracked files. Remove them from the index only:
git rm --cached .env
git commit -m "stop tracking .env"--cached removes the file from Git but leaves it on disk. For a folder, add -r: git rm -r --cached node_modules. Be careful: after a teammate pulls this commit, Git deletes their copy of the file in their working tree, so back up local config first. Without --cached, the file is deleted from disk too.
Step 4: Use .env and .env.example#
Keep real values in .env, ignored. Commit a template with the names and harmless placeholders:
# .env.example
DATABASE_URL=postgres://app:change-me@localhost:5432/app
SESSION_SECRET=change-me
SMTP_HOST=smtp.example.comNew developers run cp .env.example .env and fill in real values. On servers, supply the real file through your deploy tooling or the host’s secret store, not through Git. Replace every change-me with a long random value, such as the output of openssl rand -hex 32. See the blog post on managing secrets for self-hosted Docker for container setups.
If a secret was committed#
Work in this order:
- Rotate it now. Change the database password, revoke the API token, delete and recreate the SSH key. This is the step that actually protects you. A leaked secret is compromised from the moment it is pushed.
- Remove it from the code. Delete it, use an environment variable, add the file to
.gitignore, and commit. - Decide about history. If the repository is private and small, the rotation may be enough. For a public repository, assume the old value is already scraped. Tools such as
git filter-repocan rewrite history to remove a file or string, but they change every later commit hash, require a force push, and force every collaborator to re-clone. Cached copies and forks may still hold the old data. Read the tool’s documentation before you run it, and make a backup first. - Check logs and access. Look for use of the leaked credential between the commit and the rotation.
Pushing the removal on top of a leaked commit changes nothing for people who already have it.
The same rule applies to a public key versus a private key: the private one never goes into a repository, as covered in SSH keys and deploy keys.
Check it worked#
git status --short
git ls-files | grep -E '^\.env$'The first should not list ignored files. The second prints nothing if .env is not tracked. Also search history for a known string:
git log --all -S 'change-me' --oneline-S finds commits that added or removed that text. Use it with a snippet of a real secret locally to see whether it exists in history. Do not paste a real secret into a shared terminal log.
Edge cases and gotchas#
- Ignore rules do not rewrite history. They only prevent future adds.
- Negation needs a visible parent.
!cannot re-include a file if its parent folder is ignored. - Ignored does not mean private. A file can still end up in a Docker image if the build copies the folder. Use a
.dockerignoretoo. - Line endings in .gitignore. Trailing spaces count as part of a pattern, which makes a rule silently fail.
- Nested .gitignore files. A subfolder can have its own file with its own rules. Check all of them when something is oddly tracked.
- Public repositories are scanned. Bots look for keys within minutes. Treat any leak there as immediate.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
A file is still listed in git status after adding it to .gitignore | It is already tracked | git rm --cached file, commit |
fatal: pathspec '.env' did not match any files | The file is not tracked | It is already untracked, check git check-ignore -v .env |
The following paths are ignored by one of your .gitignore files: | git add on an ignored file | Remove the rule, or force once with git add -f if you really mean it |
error: the following file has staged content different from both the file and the HEAD | git rm --cached on a modified staged file | Use git rm --cached -f file |
fatal: not removing 'dir' recursively without -r | A folder was given | Add -r |
remote: error: GH013: Repository rule violations found or a secret scanning block | The host detected a secret in the push | Remove it, rotate it, and push again |
A pattern like *.env ignores .env.example too | Wrong pattern | Add !.env.example after it |
warning: LF will be replaced by CRLF | Line ending settings | Informational, set core.autocrlf or .gitattributes |
Quick reference#
cat .gitignore
git check-ignore -v path
git status --ignored
git rm --cached file # untrack, keep on disk
git rm -r --cached dir
git add -f file # add an ignored file anyway
git log --all -S 'text' --oneline
cp .env.example .envRelated lessons#
- Your first Git repository: what git add stages.
- Environment variables and secrets: how apps receive secrets at runtime.
- SSH keys and deploy keys for Git: keys never go in the repository.
- Undo mistakes in Git: why reverting a commit does not hide its content.
- Docker Compose environment variables: passing .env values to containers.
Next#
Put it all together in a Git workflow that triggers a deploy.
Check what you learned
Frequently asked questions
What does .gitignore do?
It tells Git which untracked files and folders to skip, so they do not show in git status and are not added by git add. It does not affect files that are already tracked.
Why is my file still tracked after adding it to .gitignore?
.gitignore only applies to untracked files. Stop tracking it with git rm --cached file, commit, and from then on it is ignored. The file stays on disk.
I committed a password to Git. What do I do?
Rotate the password right away, because anyone who saw the repository may have it. Then remove it from the code and, if needed, from history. Removing it from history alone is not enough.
Should I commit my .env file?
No. Commit a .env.example with the variable names and safe placeholder values, and keep the real .env out of Git.
Sources
Keep going: guides and tutorials
- Install a Self-Hosted PaaS on Your Own Server in Five Minutes One installer download, one setup token, one sample app. The full Levelrail install on a fresh Linux server, with the checks and the fixes.
- Deploy a Docker Compose App Self-Hosted: Web, Redis and Rollback Deploy a Docker Compose app on your own server with Levelrail: a web service and Redis, a bad release that does not take traffic, and a compose rollback.