Gitignore the .env file
Learn why a .env file must never be committed, how to ignore it with Git, and how to fix it when it was already committed
A .env file holds values that belong to one machine: local ports, local database addresses, and development passwords. Git is a tool for sharing code with other people and with the future. Those two purposes do not mix. The moment a .env file is committed, its contents are copied into the repository history, where anyone with access to the repository can read them, and where they stay even after the file is deleted. Keeping the file out of Git is a one-line change, and this page covers how to make it, how to check that it worked, and how to repair the damage when the line was added too late.
Where This Fits in Configuration
The loader reads the file and the program reads the values, but Git decides who else can read the file. A project that shares its code through Git shares everything Git tracks. The .env file is the one file in a project that must never be shared that way, because its whole job is holding values that are private to one machine.
Think of it like a house key left on a shared desk. The key is useful at home, and it is harmless while it stays in the house. The desk is where everyone in the office passes through. Putting the key on the desk does not make the key stop working, it makes the key stop being private. A .gitignore entry is the decision to keep the key off the desk.
The Smallest Working Setup
A Git project has a file named .gitignore in its root. Each line in that file is a pattern, and Git skips files whose names match a pattern. To ignore the .env file, the setup is two files:
# .gitignore
.env
# .env
APP_NAME=dotenv-demo
PORT=3000
That is the whole change. One line, in a file that is itself committed to the repository so every developer gets the same rule. Create the .gitignore file before the first commit, and the .env file never enters version control at all.
Check the result with two commands. The first asks Git whether the file is ignored:
git check-ignore -v .env
The output names the file, the line number, and the pattern that matched:
.gitignore:1:.env .env
The second asks Git what it sees as changed or untracked:
git status --porcelain
Before the ignore rule, the output lists the file as untracked:
?? .env
After the rule, the .env line disappears from the output entirely. Only the .gitignore file itself shows up as untracked, waiting to be committed. Both commands were run live against a real repository, and both behaved exactly as shown here.
Working Ignore Rule:
If git check-ignore -v .env prints the matching line and git status no longer lists .env, the file is ignored. The file still sits on disk, the program still loads it, and Git simply does not see it.
Why the File Must Never Be Committed
A .env file can hold a database password or a signing secret. Those values are secrets only while few people know them. A commit copies the file into the repository, and the repository is copied to every developer's machine, to every backup, and to every hosting service that stores it. Each copy is another place the secret lives, and none of those places is under the original developer's control.
Deleting the file later does not undo the commit. Git keeps the full history, so the committed version of the file stays readable through the log even after the file is removed from the current version. A live check confirmed this: a file committed by accident stayed visible in git ls-files and in the history after the working copy was cleaned up. The only way to remove it from history is to rewrite the history itself, which is a disruptive operation on a shared repository and still does not recall copies other people already made.
The rule follows from that. A value that has been committed is no longer a secret, and it must be treated as exposed. The repair is not only to remove the file from Git, but to change the value itself, so the exposed text stops working. The repair section below covers the exact steps.
This is also why the file must never be committed "just for now" or "just for the team". A temporary commit is still a commit, and the history keeps it. There is no safe version of committing the file. The safe version is the example file, covered below, which shares the shape of the settings without sharing any value.
How Gitignore Works
A .gitignore file is a list of patterns, one per line. Git checks each untracked file against the patterns when deciding what git status shows and what git add picks up. A line that reads .env matches a file named .env in any directory of the repository, not only in the root. That is usually what a project wants, because a nested package can have its own .env file too.
The matching rules are simple enough to use without memorising them all:
- A plain name such as
.envmatches that name in any directory. - A name with a slash, such as
config/.env, matches only at that exact path. - A
*stands for any characters, so.env.*matches.env.localand.env.productionbut not.envitself. - A
!at the start of a line makes an exception, so!.env.exampleun-ignores a file that an earlier pattern would have ignored. - A
#at the start of a line is a comment. - A blank line is skipped.
A project that uses several environment files can ignore them all with a few lines:
# .gitignore
.env
.env.local
.env.*.local
The third line covers files such as .env.development.local, which some tools create per environment. The pattern .env.* on its own would also match .env.example, which is the one file that should be committed, so a project that uses that pattern needs an exception line for the example file, or it needs to list the names it wants instead of using a wildcard.
One detail matters more than the rest. A .gitignore rule only applies to files Git is not already tracking. A file that is already committed keeps being tracked even after a matching line is added. Git does not drop a tracked file because a new rule appeared. That behaviour is the reason the repair section exists, and it was verified live: a committed .env file stayed in git ls-files and stayed out of git status output after the ignore rule was added, because Git considered it unchanged and tracked.
Adding the Rule to a Project
The steps depend on where the project stands. A new project gets the rule before its first commit, which is the easy case. An existing project gets the rule now and checks that nothing was already committed, which is the case that needs care.
A New Project
Create the .gitignore file in the project root, add the line, and commit the file:
git add .gitignore
git commit -m "Ignore local environment files"
The .env file itself is never added. It stays on disk, untracked and invisible to Git, and the program keeps loading it exactly as before. The .gitignore file is committed so that every developer who clones the project gets the same protection automatically.
An Existing Project
Add the line to .gitignore and then check whether the damage is already done:
git ls-files | grep env
If the command prints nothing, no environment file is tracked, and the rule is enough. If it prints .env, the file was already committed, and the repair section below applies. The check takes a second and saves a project from shipping a secret it believes is protected.
The Rule Protects the Future, Not the Past:
A .gitignore entry stops future commits from including the file. It does not remove a file that is already in the history, and it does not change values that were already exposed. The check above tells the reader which situation they are in.
Checking That the File Is Really Ignored
Three commands together give a complete answer, and each one checks a different thing.
The first asks Git directly whether the file matches an ignore rule:
git check-ignore -v .env
The -v flag makes Git print the file and line that matched, such as .gitignore:1:.env. If the command prints nothing and exits with status 1, the file is not ignored. That exit code is how scripts test the result: an exit code of 0 means ignored, and 1 means not ignored. A live run before the rule was added printed nothing and exited with 1. A live run after the rule printed the matching line.
The second checks what Git sees in the working directory:
git status --porcelain
An ignored file does not appear in this output at all. A tracked file appears only when it has changes. A file that is neither ignored nor tracked appears with ?? in front of its name, which is Git's mark for an untracked file. The .env line should be absent from this output. If it shows ?? .env, the ignore rule is missing or misspelt.
The third lists what Git is actually tracking:
git ls-files | grep env
This is the check that catches the dangerous case. A tracked .env file appears here even when an ignore rule exists, because ignore rules do not apply to tracked files. If .env appears in this list, the file is in the repository, and the ignore rule is not protecting it.
Step 1: Ask Git whether the file is ignored
Run git check-ignore -v .env in the project root. A matching line means the rule exists. No output means it does not.
git check-ignore -v .env
Step 2: Check the working directory
Run git status --porcelain. The .env file should not appear at all. A ?? .env line means the file is untracked and unignored.
git status --porcelain
Step 3: Check what Git is tracking
Run git ls-files | grep env. The .env file should not appear. If it does, the file was committed before the rule existed and needs the repair below.
git ls-files | grep env
The .env.example File
A new developer who clones the project needs to know which settings the program reads, but they must not receive the values. The .env.example file solves that. It lists every key the program reads, with an empty value or an obviously fake placeholder, and it is committed to the repository:
# .env.example
APP_NAME=
PORT=
DATABASE_URL=
A new developer copies it and fills in their own values:
cp .env.example .env
The copy is the private file, and the example is the shared template. The example file documents the settings, and it gives the program's startup check something to compare against, since a key missing from the example is a key a new developer will not know to set.
The example file needs its own care. Its values must be empty or obviously fake, such as change-me-locally or postgres://dev-user:change-me-locally@127.0.0.1:5432/demo-db. A real password in the example file is the same mistake as a real password in the .env file, because the example file is committed. A reviewer reading the example file should be able to tell at a glance that no value in it is real.
The ignore rule must not swallow the example file. A pattern such as .env.* matches .env.example, so a project using that pattern needs an exception line after it:
# .gitignore
.env.*
!.env.example
The ! line un-ignores the example file. The order matters: the exception must come after the pattern it overrides. A project that lists names one by one, such as .env and .env.local, does not need the exception at all.
What Happens When the File Was Already Committed
A file that is already tracked needs three actions: stop tracking it, commit that change, and change every secret value it contained. The first two repair the repository. The third repairs the exposure, because the old values remain readable in the history.
The command that stops tracking a file without deleting it from disk is:
git rm --cached .env
The --cached flag tells Git to remove the file from its index, which is the list of tracked files, while leaving the working copy alone. The file stays on disk, the program keeps loading it, and Git stops tracking it. Without the flag, git rm .env would delete the file from disk too, and the developer would lose their local settings.
After the removal, commit the change:
git commit -m "Stop tracking local environment file"
The commit records that the file is no longer tracked. From this commit onward, the file is untracked, and the ignore rule in .gitignore keeps it that way. A live run of these two commands confirmed the result: git ls-files no longer listed .env, git status showed nothing, and the file was still on disk with its contents intact.
The third action is the one beginners skip, and it is the most important. Every secret value that was in the committed file must be changed, because anyone with a copy of the history can still read the old value. A database password must be changed on the database. A signing secret must be replaced wherever it was used. A key for an external service must be revoked and reissued. Removing the file from Git does not recall the copies that already left the machine.
Removing the File Does Not Unshare the Secret:
git rm --cached stops future commits from including the file, and the old commits still hold it. The values in those commits are readable by anyone with the history. Change every secret that was in the file, or the removal is only cosmetic.
Rewriting history to erase the file from old commits is possible with tools built for that job, but it is a disruptive operation on a shared repository, it forces every developer to re-clone or rebase, and it still does not recall copies other people already made. Changing the exposed values is the reliable repair. History rewriting is a separate decision for the team, and it does not replace rotating the secrets.
A Realistic Complete Setup
The setup below is a realistic project root. The .gitignore file protects the private files and shares the example file. The .env file holds local values. The .env.example file documents the shape:
# .gitignore
.env
.env.local
!.env.example
# .env
APP_NAME=dotenv-demo
PORT=3000
DATABASE_URL=postgres://dev-user:change-me-locally@127.0.0.1:5432/demo-db
# .env.example
APP_NAME=
PORT=
DATABASE_URL=
The three checks against this setup give three clean answers. git check-ignore -v .env prints the matching line from .gitignore. git status --porcelain shows no .env line, and shows .env.example as a file to commit. git ls-files after committing shows .gitignore and .env.example, and never .env.
A second project layout uses a wildcard instead of listing names. The wildcard version needs the exception line, and it protects files the team has not thought of yet:
# .gitignore
.env*
!.env.example
The * matches .env, .env.local, and .env.production, and the exception keeps the example file committed. Either layout works. The listed-names version is clearer about what it protects, and the wildcard version is safer against a new file name appearing later. A project should pick one and keep it consistent.
Testing the Ignore Rule
A test for the ignore rule is a shell script rather than a Rust test, because the rule belongs to Git, not to the program. The script below creates a temporary repository, adds the rule, and checks the three commands from the checking section:
#!/bin/bash
set -e
rm -rf /tmp/gitignore-test
mkdir /tmp/gitignore-test
cd /tmp/gitignore-test
git init -q -b main .
git config user.email "test@example.local"
git config user.name "Test"
printf 'APP_NAME=dotenv-demo\nPORT=3000\n' > .env
printf '.env\n' > .gitignore
# The file must be ignored.
git check-ignore -v .env
# The file must not appear in status output.
if git status --porcelain | grep -q '^\?\? .env$'; then
echo "FAIL: .env is not ignored"
exit 1
fi
# The file must not be tracked.
if git ls-files | grep -q '^\.env$'; then
echo "FAIL: .env is tracked"
exit 1
fi
echo "PASS: .env is ignored and untracked"
Run it with:
bash gitignore-test.sh
The script uses set -e, which stops it at the first failing command, so a missing ignore rule fails at the check-ignore step before the later checks run. The grep -q checks look for exact matches, so a file named .env.example does not trigger them. The script was run live and printed PASS: .env is ignored and untracked.
Common Beginner Mistakes
Committing the File Before Adding the Rule
# Wrong order - the file enters history before the rule exists
git add .env
git commit -m "Add settings"
The fix is the repair from the section above: add the rule, run git rm --cached .env, commit the removal, and change every secret value the file contained. Adding the rule after the commit does not help on its own, because the file is already tracked.
Deleting the File Instead of Untracking It
# Wrong - deletes the local settings from disk
git rm .env
The fix is the --cached flag:
# Correct - stops tracking, keeps the file on disk
git rm --cached .env
The wrong command removes the file from the working directory, and the developer loses their local settings. The file can be recreated from the example file, but the values in it are gone. The --cached flag is the difference between removing a file from Git and removing it from the machine.
A Misspelt Pattern
# Wrong - a typo means nothing matches
# .gitignore
.envv
The file .envv does not exist, so the rule matches nothing, and .env stays visible in git status. The fix is the check command: git check-ignore -v .env prints nothing when the pattern is wrong, and that silence is the signal to read the .gitignore file again.
Ignoring the File in Only One Clone
A .gitignore file that is never committed protects only the machine it was written on. Every other developer who clones the project gets no rule, and the first one who runs git add . commits their own .env file. The fix is to commit the .gitignore file itself. It is a shared project file, and it belongs in the repository.
Trusting a Global Ignore File Alone
Git supports a global ignore file that applies to every repository on a machine. It is a useful safety net, and it is not a replacement for a project .gitignore file. The global file protects one machine. The project file protects every machine that clones the project. A project should carry its own rule, and the global file is only a backup.
git add . Adds Everything Not Ignored:
The command git add . adds every untracked file that is not ignored. A missing or misspelt ignore rule turns one careless command into a committed secret. Run git status before git add . in a new project, and read the list of files it is about to add.
Final Complete Example
The final example gathers the whole setup into one project root, with the commands that prove each part works:
# .gitignore
.env
.env.local
!.env.example
# .env
APP_NAME=dotenv-demo
PORT=3000
DATABASE_URL=postgres://dev-user:change-me-locally@127.0.0.1:5432/demo-db
# .env.example
APP_NAME=
PORT=
DATABASE_URL=
git check-ignore -v .env
git status --porcelain
git ls-files | grep env
The expected output is:
.gitignore:1:.env .env
The git status output shows the .gitignore and .env.example files as new files to commit, and no line for .env. The git ls-files output, after committing, lists .gitignore and .env.example, and never .env. That combination is the whole goal: the private file stays on the machine, the template is shared, and the rule that separates them is committed with the code.
Summary
The ignore rule is one line, and the thinking behind it is the difference between a file and a secret. A file is private while it stays on one machine. A commit copies it to every machine that holds the repository, and the history keeps the copy after the file is gone. The rule keeps the file on its machine, the example file shares the shape without sharing any value, and the three check commands prove the separation instead of assuming it.
The decision framework is short. If a value belongs to one machine, it lives in .env and .env lives in .gitignore. If a value belongs to every developer, it lives in .env.example with an empty or fake value, and that file is committed. If a file was already committed, the repair is untracking it with --cached, committing the removal, and changing every secret it held, because the history does not forget. Once that split is in place, the settings are private where they should be private and shared where they should be shared.