---
title: "Git清除提交历史撤销已提交的敏感信息 | Kaz"
description: 暫無摘要
canonical_url: "https://unmei.fun/zh-Hant/blog/202608172304"
locale: zh-Hant
meta:
  "og:description": page.blog.202608172304.desc
  "og:image": "https://unmei.fun/favicon.svg"
  "og:image:height": "630"
  "og:image:width": "1200"
  "og:title": page.blog.202608172304.title
---

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

當前頁面所支持的語言：

简体中文

# **Git清除提交历史撤销已提交的敏感信息**

字數 1446

大約耗時 6 minutes

2026年8月17日週一 15:04:00 \[UTC]

> **⚠️ 警告**：此操作会改写提交历史，强制推送后远程仓库中指定提交之后的记录将永久消失。 仅建议在个人仓库或确认无人使用该分支时使用。多人协作场景请优先考虑 `git revert`。

## 适用场景

误把密钥、密码、Token 等敏感信息提交进了仓库，需要把这些提交从历史中彻底移除。注意：**一旦推送到公开仓库，就应当立即视为密钥已泄露并更换**，清理历史只能减少后续被扫描到的风险，不能挽回已经发生的泄露。

## 操作流程

### 1. 找到要回退到的提交 ID

在 **GitHub Desktop** 中查看历史记录，复制目标提交的 SHA。

或在终端查看最近提交：

```sh
git log --oneline -10
```

### 2. 硬回退到指定提交

```sh
git reset --hard <提交ID>
```

示例：

```sh
git reset --hard a1b2c3d
```

`--hard` 会同时重置暂存区和工作区，未提交的改动会被丢弃，执行前请确认没有需要保留的内容。

### 3. 确认回退结果

```sh
git log --oneline -5
git status
```

此时通常会看到类似提示：

```sh
Your branch is behind 'origin/main' by X commits, and can be fast-forwarded.
```

这说明本地已经回退，但远程还保留着旧的提交。

### 4. 强制推送到远程（覆盖历史）

推荐使用更安全的写法：

```sh
git push --force-with-lease
```

如果确定没有问题，也可以直接：

```sh
git push --force
```

## 补充说明

- `--force-with-lease` 会检查远程是否有你本地不知道的新提交，比裸 `--force` 更安全。多人协作时至少要用这一种。
- 如果误操作想找回丢失的提交，可立即使用：

  ```sh
  git reflog
  ```

    
  找到对应记录后再次 `git reset --hard` 即可恢复。 `reflog` 默认保留 90 天，但只存在于本地，远程被覆盖的提交无法通过它找回。
- 只想撤销某一次提交、保留后续历史时，应使用 `git revert <提交ID>`，它会生成一个新的反向提交，不改变已有历史。
- 如果敏感信息已经存在于多个分支或标签中， `reset` 只能处理当前分支。更彻底的做法是使用 `git filter-repo` 重写整个仓库历史，并在清理后强制推送所有分支和标签。
- 清理完成后，别忘了在 GitHub 等平台撤销旧的访问令牌、更换泄露的密钥，并检查 Actions 日志、缓存中是否也留有记录。

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://unmei.fun/zh-Hant#website","@type":"WebSite","inLanguage":"zh-Hant","name":"HomePage","url":"https://unmei.fun/zh-Hant","translationOfWork":{"@id":"https://unmei.fun/#website"}},{"@id":"https://unmei.fun/zh-Hant/blog/202608172304#webpage","@type":"WebPage","description":"暫無摘要","name":"Git清除提交历史撤销已提交的敏感信息","url":"https://unmei.fun/zh-Hant/blog/202608172304","breadcrumb":{"@id":"https://unmei.fun/zh-Hant/blog/202608172304#/schema/breadcrumb-list/#breadcrumb"},"isPartOf":{"@id":"https://unmei.fun/zh-Hant#website"},"potentialAction":[{"@type":"ReadAction","target":["https://unmei.fun/zh-Hant/blog/202608172304"]}]},{"@id":"https://unmei.fun/zh-Hant/blog/202608172304#/schema/breadcrumb-list/#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Home","item":"https://unmei.fun/zh-hant","position":1},{"@type":"ListItem","name":"Blog","item":"https://unmei.fun/zh-hant/blog","position":2},{"@type":"ListItem","name":"202608172304","item":"https://unmei.fun/zh-hant/blog/202608172304","position":3}]}]}
```

## Sitemap

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