How do I ignore .env but keep .env.example?

For projects using local .env files, keep real values outside version control and share a reviewed .env.example containing placeholders. Check your framework’s configuration conventions before applying a broad rule.

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.example

The !/.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

Why does ! fail to keep a file inside an ignored directory?

3. Handle previously tracked values

Check whether Git already tracks either local values file:

git ls-files -- .env .env.local

If 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.

How do I ignore files Git already tracks?

For exact behavior and further details, consult the official references: Git documentation · Git FAQ · GitHub guidance on exposed sensitive data