---
title: "วิธีการลบ .env file ออกจาก git แบบถูกวิธี"
description: "สมมติว่าเราเผลอ commit ไฟล์ .env ที่มี API key ไปแล้ว และ push ขึ้น GitHub เราต้องรีบลบมันออกทันที เพราะข้อมูลอาจถูกนำไปใช้ได้"
canonical_url: "https://iamthana.com/blogs/2025-04-14-dotenv-leak-lab"
---

> Index of every page on this site: [llms.txt](https://iamthana.com/llms.txt)

![.env leak](https://iamthana.com/images/2025-04-14-dotenv-leak-lab/image-0.png)

สมมติว่าเราเผลอ commit ไฟล์ .env ที่มี API key ไปแล้ว และ push ขึ้น GitHub เราต้องรีบลบมันออกทันที เพราะข้อมูลอาจถูกนำไปใช้ได้

สำหรับวิธีการลบ .env file แบบถูกวิธีให้ทำแบบนี้นะครับ พร้อมแล้วไปลุยกันเลยย

## 1. นำ .env file ไปใส่ใน `.gitignore` ก่อน

```sh [.gitignore]
.env
.env.*
```

> .env.:* เช่น .env.production .env.local .env.development

แนะนำให้ลองใช้ [https://www.toptal.com/developers/gitignore](https://www.toptal.com/developers/gitignore) ผมใช้เป็นประจำครับ เป็นเครื่องมือในการช่วยสร้าง gitignore ไฟล์ชั้นดีเลย

## 2. ลบ .env file ออกจาก git แบบในทุก ๆ commits

```sh
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch .env" HEAD
```

![Output](https://iamthana.com/images/2025-04-14-dotenv-leak-lab/image-1.png)

ถ้าลบออกเฉย ๆ ด้วยคำสั่ง `git rm -r --cached .env` หรือ `rm .env` แล้ว commit ไปใหม่ สิ่งที่จะเกิดขึ้นคือไฟล์จะหายไปแค่ commit ล่าสุดเท่านั้น แต่ถ้าไปดูใน commit history ไฟล์ดังกล่าวจะยังอยู่ครับ

## 3. push .git ไฟล์อันใหม่ขึ้นไปด้วยคำสั่ง

> คำเตือน: คำสั่งนี้จะเปลี่ยนแปลงประวัติทั้งหมดของ Project ควรแน่ใจว่าไม่มีใครใช้งาน repository นี้อยู่ก่อนจะ push ด้วย --force

```sh
git push origin main --force
```

![Result](https://iamthana.com/images/2025-04-14-dotenv-leak-lab/image-2.png)

เพียงแค่นี้ `.env` file ก็จะถูกลบออกไปจาก Git ของเราเรียบร้อยแล้วครับ

> Tip: ถ้าเคย push .env ขึ้น GitHub, Gitlab, Gitea หรือ Git Platform อื่น ๆ แล้ว อย่าลืมรีเซ็ต API key หรือ Token ที่อยู่ในไฟล์ด้วยนะครับ เพื่อความปลอดภัยสูงสุด

## Sitemap

See the full [sitemap](https://iamthana.com/sitemap.md) for all pages.
