1. Ignore local values and retain the example
Put these rules in the root .gitignore. They cover .env and root files beginning .env., then re-include .env.example. They do not cover names such as service.env or files in nested directories.
Review .env.example before committing it: an example filename does not guarantee that its values are safe to publish. Use placeholder values and document required variables.
/.env
/.env.*
!/.env.example 2. Verify all three cases
With untracked .env, .env.local and .env.example present, inspect the matching rules:
git check-ignore -v -- .env .env.local .env.exampleThe !/.env.example line means the example is re-included. Status should list that example while omitting the two local value files. An excluded parent directory or later rule can still change the result.
git status --short --untracked-files=all -- .env .env.local .env.example 3. Handle previously tracked values
Check whether Git already tracks either local values file:
git ls-files -- .env .env.localIf paths appear, follow the tracked-files article and coordinate changes with collaborators. Adding .gitignore does not remove existing commits. If a credential was exposed, revoke or rotate it first and follow GitHub’s sensitive-data guidance; removing the current file alone does not erase history.
For exact behavior and further details, consult the official references: Git documentation · Git FAQ · GitHub guidance on exposed sensitive data