.gitignore isn't enough: how secrets still end up in git
.gitignore does one thing: it stops git from starting to track files that match a pattern. It does nothing for a file git already tracks, nothing when you add a file with -f, nothing for a file name the pattern doesn't match, and nothing outside git, such as npm publish with its own ignore file. That's why .env files keep turning up in repositories that "ignore" them.
I ran every command below in a test repository with made-up keys, so the output is real. The post covers the ways a key gets past .gitignore, how to check every branch for one, and the fix, including a side effect of git rm --cached that hits your teammates.
Why doesn't .gitignore stop a .env file I already committed?
Because ignore rules only apply to untracked files. The gitignore documentation says so in its first lines: "A gitignore file specifies intentionally untracked files that Git should ignore. Files already tracked by Git are not affected."
The common sequence: someone runs git add . in a new project before the ignore rule exists, then adds .env to .gitignore a day later. From then on, git keeps tracking every change to the file:
$ git status --short
M .env
$ git check-ignore -v .env
$ git check-ignore -v --no-index .env
.gitignore:1:.env .envgit check-ignore prints nothing for .env, because a tracked file isn't subject to ignore rules. With --no-index it shows the rule that would apply if the file weren't tracked. The rule is fine; it came too late.
Which .gitignore patterns miss .env files?
Small differences in a pattern decide which files it covers. I tested each one against .env, .env.local, .env.production, .env.example, prod.env and services/api/.env:
| Pattern | Ignores | Misses |
|---|---|---|
.env |
.env at any depth |
.env.local, .env.production, prod.env |
/.env |
.env in the repository root only |
services/api/.env and every variant |
*.env |
.env, prod.env |
.env.local, .env.production |
.env* |
every .env… file, .env.example too |
prod.env |
The git docs explain the second row: "If there is a separator at the beginning or middle (or both) of the pattern, then the pattern is relative to the directory level of the particular .gitignore file itself. Otherwise the pattern may also match at any level."
This block covers all of them and keeps the example file:
.env
.env.*
*.env
!.env.exampleWith it, .env.local, .env.production, .env.bak and prod.env are all ignored, and only .env.example shows up as a file you can commit.
What other traps let a .env file through?
A comment on the same line. Git treats a line as a comment only when it starts with #. Anything after the pattern becomes part of the pattern, so this rule matches nothing:
$ cat .gitignore
.env # local keys, never commit
$ git check-ignore -v .env
$ git status --short
?? .env
?? .gitignorePut comments on their own line.
git add -f. Git warns you once, then does what you asked:
$ git add .env.local
The following paths are ignored by one of your .gitignore files:
.env.local
hint: Use -f if you really want to add them.
hint: Disable this message with "git config set advice.addIgnoredFile false"
$ git add -f .env.localThe hint is easy to follow without thinking, especially when a script or a tutorial told you to use -f for something else.
A rule that only lives on your machine. Patterns in .git/info/exclude or in your global ignore file (core.excludesFile, by default ~/.config/git/ignore) work for you and nobody else. A teammate's clone, a CI job or a fresh checkout on your next laptop doesn't have them. The git docs say patterns "that all developers will want to ignore" belong in a .gitignore file in the repository.
Copies with other names. .env.backup, env.txt, config.local.json, or a .envrc for direnv: each is a copy of the same keys under a name your rules may not cover. The .env.* line catches the first; the others need their own lines, or better, no copy at all.
Keys inside files you have to commit. .gitignore can't help with an API key typed into docker-compose.yml, settings.py, terraform.tfvars, a notebook's saved output, or an .npmrc with an auth token. Those files are tracked on purpose, so the key goes wherever the file goes.
Which tools ignore your .gitignore?
.gitignore is read by git. Other tools that package or copy your project folder have their own rules:
npm publishandnpm pack. npm's docs say that if a package has a.gitignorebut no.npmignore, npm uses the.gitignorerules. Add a.npmignorefor any reason, and npm uses that instead. Here's what that does to a package whose.gitignorelists.env:$ npm pack --dry-run 2>&1 | grep -A4 "Tarball Contents" npm notice Tarball Contents npm notice 20B index.js npm notice 56B package.json npm notice 5B tests/a.test.js npm notice Tarball Details $ echo 'tests/' > .npmignore $ npm pack --dry-run 2>&1 | grep -A4 "Tarball Contents" npm notice Tarball Contents npm notice 32B .env npm notice 20B index.js npm notice 56B package.json npm notice Tarball DetailsExcluding the tests folder put
.envinto the package. Afileslist inpackage.json, which names what to include, avoids the whole problem.docker build. The builder looks for a.dockerignorein the root of the build context (Docker docs). Without one,COPY . .copies your.envinto the image. The post on how .env files leak covers Docker in more detail.zip, rsync and scp. A zip of the project folder for a contractor includes every file in it.
git archive HEAD -o src.zipis the safer way to share source, because it includes tracked files only.AI coding agents. Claude Code's Read tool opens
.gitignored files;.gitignoreonly hides them from its file picker. The post on Claude Code's permissions shows the deny rules that do block them.
How do I check if a .env file is in my git history?
Run these from the repository root. They check every branch, not only the one you're on:
# env files git tracks right now
$ git ls-files | grep -E "(^|/)\.env"
.env
services/api/.env.local
# every commit on every branch that added, changed or removed one
$ git log --all --oneline --name-status -- '*.env*'
ec54e93 Add API service
A services/api/.env.local
0af4dca Initial commit
A .env
# commits that added or removed a known key name, in any file
$ git log --all --oneline -S STRIPE_KEY
0af4dca Initial commitThe second command is the important one. A .env file deleted three months ago still shows up there, with the commit that added it, and so does the copy in services/api/ that nobody remembers. The third finds keys outside .env files, for example in a config file that's tracked on purpose. Search for the names of your keys or for a provider's prefix, such as sk_live_ for Stripe live keys.
To see what is ignored right now, and by which rule:
$ git status --short --ignored
$ git check-ignore -v services/api/.env.local
.gitignore:2:.env.* services/api/.env.localHow do I fix a .env file that's already in git?
Do it in this order. The first step is the one that makes the key safe; everything after it is cleanup.
Rotate the key. Assume anyone who has a copy of the repository has the key. Create a new key, deploy it, then revoke the old one. The post on leaked keys has the rotation steps and links per provider.
Stop tracking the file.
git rm --cachedremoves it from the index and leaves your copy on disk:$ git rm --cached .env services/api/.env.local rm '.env' rm 'services/api/.env.local' $ git commit -m "Stop tracking .env files"Fix the patterns with the block above, and commit
.gitignorein the same commit.Warn your teammates before they pull. This is the side effect nobody mentions. When a teammate pulls a commit that stops tracking
.env, git deletes their copy of the file if they hadn't changed it. If they had changed it, the pull stops instead:$ git pull Updating 1f16b1d..73e6cdf error: Your local changes to the following files would be overwritten by merge: .env Please commit your changes or stash them before you merge. AbortingAsk them to copy their
.envsomewhere outside the repository first, pull, and copy it back. (Better still, this is a good moment to stop sharing one file.)Decide about history. The key is still in old commits. Rewriting history is a separate job with its own costs, and it doesn't reach copies you don't control: GitHub's guide to removing sensitive data says "If the commit that introduced the sensitive data exists in any forks, it will continue to be accessible there." That's why rotating comes first.
How do I stop it happening again?
- Commit
.gitignorebefore the first.envexists. In a new project, write the ignore block in the first commit, then create the file. - Commit a
.env.examplewith names and placeholder values, so nobody needs the real file to know which keys a project uses. - Add a second net. A pre-commit hook that scans for secrets, or GitHub's push protection on the repository, catches the cases the patterns miss.
- Keep keys out of the project folder. A key that lives in an encrypted vault and reaches your app when it starts can't be committed, packed or zipped by accident. That's how I use Keyfold: keys by project and environment, given to a command at run time with
keyfold run, and no.envfile in the repository at all. If a tool needs a file, Keyfold can export one, and you delete it afterwards. Keyfold's own leak check and pre-commit hook are on the roadmap, not in the app yet.
Browse the demo vault in the live demoOpens the live demo, with made-up keys
FAQ
Does adding .env to .gitignore remove it from git?
No. It only stops git from starting to track it. If the file is already tracked, run git rm --cached .env, commit, and rotate any key it held.
Why does git status still show my .env file as modified?
Because git is tracking it. Ignore rules apply only to untracked files, so a tracked file keeps showing changes until you stop tracking it with git rm --cached.
Does .gitignore apply to every folder in the repository?
A pattern without a slash, such as .env, matches at any depth below the .gitignore that contains it. A pattern with a leading slash, such as /.env, matches only at that level. A .gitignore in a subfolder applies only inside that folder.
Is a .env file in a private repository a problem?
Yes, if it holds real keys. Everyone with access, every clone, CI system and backup has them, and a private repository can become public or be forked inside an organisation. Keep keys out of the repository and rotate any that were committed.
Can I keep using .env files safely?
For test keys, with the patterns above, a .env.example and a second net, yes. For keys that matter, load them at run time from an encrypted store instead. The features page shows how Keyfold imports a .env file once so you can delete the plain copy.