'git ignore .env files not working

I have a laravel project. In the root directory are these 4 files:

.env .env.example .env.local .env.staging

I have a .gitignore file, and I'm listing these 4 files in the .gitignore, one after another, like this

.env
.env.example
.env.local
.env.staging

My git repository does not contain .env or .env.example, but it DOES contain .env.local and .env.staging. I've tried everything I can think of, but it keeps syncing these 2 files with Gitlab.

Any ideas what could be causing this?

Thanks for your help!



Solution 1:[1]

Use git rm:

If you have already added the files to be tracked, you need to remove them from tracking:

git rm env.local --cached
git rm env.staging --cached
git commit -m "Stopped tracking env.local, and env.staging"

Now you should be able to clone your branch without those files being tracked.

Note: Keep in mind that the contents of those files are in your history, and if they did contain sensitive data, then you need to completely remove that from history before putting it out there.

Solution 2:[2]

Simply Run This Command.

git rm .env --cached
git commit -m "Stopped tracking .env File"

In laravel there are .env file include for connecting database. So for that you must remove .env file from cached.

Solution 3:[3]

It is because your .env file has been pushed to git.

You should first delete that from git and push your changes.

rm -f .env
git add .
git commit -m "remove .env file from git"
git push

Solution 4:[4]

You can remove that file from cached.

try below command

git rm .env --cached
git commit -m "Any message"

Solution 5:[5]

No need to use clear cache command, there's much simpler solution also doable in GUI.

If you are absolutely sure, your .gitignore rule is correct:

  1. stage the file that is not being ignored (STAGE ONLY DON'T COMMIT)
  2. unstage the file
  3. The file should not appear in changes anymore

Solution 6:[6]

The best solution is to put the .env file in it's own folder, then add that folder to the .gitignore file. example:

  • create a folder called "vars"
  • move your .env file into that folder
  • add the vars folder in .gitignore
*inside .gitignore*

/node_modules
/vars

-Make sure you add the path to dotenv.config() in your main file where you use the enviroment variables

dotenv.config({path: "./vars/.env"}

Then you can continue to reference you environment variables the same way as before

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 4b0
Solution 3 hamed dehghan
Solution 4 Manjeet Kumar Nai
Solution 5 jave.web
Solution 6 Kwanele Gamedze