1011 字
5 分鐘
疑難雜症

分享一些建站時遇到的奇怪小問題


Git推送問題#

概述#

我最初打算效仿Fuwari搭建的經驗,本地修改後,使用Git Push推送至Github庫,最後使用Cloudflare Pages完成網頁展示。然而,Git Push 指令失敗了。

1. Could not read from remote repository.錯誤#

  • 錯誤信息:

    ERROR: Permission to Cooper1896/Hexo.git denied to deploy key
    fatal: Could not read from remote repository.

這是本次排查的核心問題。信息指出,Git 正在使用一個部署密鑰進行身份驗證,但最終無法讀取遠程倉庫。

部署密鑰是綁定在單個倉庫上的,用來拉取代碼。鑑於我在搭建Fuwari時也是創建了密鑰後,通過SSH把文件推送至庫,此時我就有了第一個猜想:生成的密鑰已經被F庫所佔用

  • 嘗試解決

    1. 棄用部署密鑰: 在倉庫的 Settings -> Deploy keys 中刪除了該密鑰。

    2. 生成新的個人密鑰: 創建了一個新的、專用於個人身份驗證的 SSH 密鑰對 (id_hexoid_hexo.pub)。

    3. 綁定個人密鑰: 將新公鑰 (id_hexo.pub) 添加到 GitHub 個人賬户的 Settings -> SSH and GPG keys 中。

1.1 本地 SSH 客户端配置#

  • 錯誤信息:
ERROR: Permission to Cooper1896/Hexo.git denied to deploy key
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

即使生成了新密鑰並添加到了 GitHub 賬户,系統在 git push 時仍然可能嘗試使用舊的(或默認的)密鑰。這是因為新密鑰的文件名 (id_hexo) 不是 SSH 客户端的默認名稱(id_rsa)。

  • 解決方案:

    1. 創建並編輯了本地 SSH 配置文件,在 config 文件中添加了以下內容,強制 SSH 客户端在連接 github.com 時使用新創建的私鑰:

      Host github.com
      HostName github.com
      User git
      IdentityFile 'ssh密钥地址'

1.2 GitHub 推送保護#

搞定了密鑰,再次push,再次彈出錯誤信息:

  • remote: error: GH013: Repository rule violations found...
    remote: - GITHUB PUSH PROTECTION
    remote: - Push cannot contain secrets
    remote: —— GitHub Personal Access Token ——————————————————————
    remote: locations:
    remote: - commit: 1659a89...
    remote: path: Pic_Github_Token.txt:1
    ! [remote rejected] main -> main (push declined due to repository rule violations)

原因是因為身份驗證成功後,推送被 GitHub 的安全策略阻止。GitHub 的掃描功能檢測到我嘗試推送的某個提交 (1659a89...) 中,有一個名為 Pic_Github_Token.txt 的文件包含了一個 GitHub 個人訪問令牌 (PAT)。

好嘛,此時我有兩個選擇:

  1. 撤銷令牌

  2. 清理歷史: 使用git revert 從本地 Git 歷史中徹底移除了包含該機密的文件和提交。

  3. 繞過: 選擇訪問錯誤信息中提供的特定 URL,在 GitHub 界面上選擇“允許推送該機密”(但該文件會永久公開在倉庫歷史中)。

貌似最好的選擇是選項2,逐選擇2

1.3 Updates were rejected#

  • 錯誤信息:

    ! [rejected] main -> main (non-fast-forward)
    hint: Updates were rejected because the tip of your current branch is behind
    hint: its remote counterpart. Use 'git pull' before pushing again.

看起來遠程倉庫已經接收到了新的提交請求。但是因為本地分支落後於遠程分支,Git 拒絕了直接推送以防止覆蓋遠程更改。

  • 解決方法:執行 git pull origin main,嘗試將遠程的更改拉取併合併到本地。

1.4 拒絕合併不相關的歷史#

  • 錯誤信息:

    fatal: refusing to merge unrelated histories

在執行 git pull 時觸發了此錯誤。這個問題我想半天不知道怎麼解決,逐問AI…

核心問題在於我的本地倉庫是使用 git init 獨立初始化的,而遠程 Cooper1896/Hexo 倉庫是在 GitHub 上獨立初始化的。它們沒有共同的原始提交,Git 默認拒絕合併兩個完全不相關的項目。

  • 解決方案:

    1. 使用 --allow-unrelated-histories 標誌強制 Git 合併這兩個不同的歷史記錄:

      git pull origin main --allow-unrelated-histories
    2. Git 自動打開了文本編輯器(Vim/Nano),要求為這次合併提供一個提交信息。

    3. 通過保存並退出編輯器( :wq),完成了合併提交。

    至此終於解決…


疑難雜症
https://brizen.dpdns.org/posts/web-troubleshooting/
作者
Cooper Liu
發佈於
2025-11-28
許可協議
CC BY-NC-SA 4.0