.gitignore Generator · Tutorial

How to stop committing .env files and secrets to git

6 min readbeginnerUpdated

Your project keeps API keys in a .env file and you want to be sure it never reaches GitHub. You will add the right rules, keep a safe .env.example for teammates, and fix the case where .env was already committed.

What you need

Steps

  1. Include the secrets rules

    Load the example and check that Secrets (.env files) is ticked. It adds .env and .env.* to ignore every environment file, then !.env.example to keep the example.

    .env
    .env.*
    !.env.example
  2. Test the rules

    In Is this path ignored? type .env.local: it is ignored by .env.*. Now type .env.example: it is not ignored, because the ! line comes later and the last match wins.

  3. Save the file

    Download the result and save it as .gitignore in the repository root. Run git status: the .env file no longer appears as a new file.

  4. Fix an already-tracked .env

    If .env was committed before, git keeps tracking it. Remove it from the index without deleting it from disk, then commit.

    git rm --cached .env
    git commit -m "Stop tracking .env"
  5. Rotate the exposed secrets

    A committed secret stays in the repository history even after this. If the repository was ever pushed, create new keys and revoke the old ones.

Try it yourself

Opens the .gitignore Generator with this tutorial's sample loaded.

Try it now

Common mistakes

Putting the rule below a broader !
The last matching line wins. A later line such as !*.local would bring .env.local back. Keep the secrets rules after general rules.
Expecting .gitignore to remove history
Ignoring a file only affects the future. Rotating the secret is the only safe fix once it has been pushed.

Next steps

Go back to the .gitignore Generator, or keep going with one of these:

FAQ

Should I commit .env.example?

Yes. List every variable your app needs with dummy values, so teammates know what to fill in.