更新(2026-07-11):修正
includeIf条件关键字为hasconfig:remote.*.url,并补充 HTTPS/SSH 匹配、配置来源检查和适用边界。
我同时维护 GitHub 公共仓库和公司内网仓库,两边使用的提交姓名和邮箱不同。每个仓库手动执行 git config user.email ... 可以解决,但新 clone 一个仓库后很容易忘,提交记录也可能因此混用身份。
Git 的 includeIf 可以按远程 URL 条件加载不同的配置文件。下面这套配置同时覆盖 HTTPS 和 SSH;示例来自 macOS 上的 Git 2.49.0。
配置关系
~/.gitconfig
├── 匹配 GitHub remote -> ~/.gitconfig-github
└── 匹配公司 remote -> ~/.gitconfig-work
全局文件保留默认身份,子配置只覆盖 user.name 和 user.email。这里使用的条件关键字必须写成 hasconfig:remote.*.url。remote.*.url 会检查仓库里配置的远程地址,不只检查名为 origin 的 remote。
1. 全局配置 ~/.gitconfig
[user]
name = example
email = example@dev.com
[init]
defaultBranch = main
[credential]
helper = osxkeychain
# GitHub: HTTPS
[includeIf "hasconfig:remote.*.url:https://github.com/**"]
path = ~/.gitconfig-github
# GitHub: SSH
[includeIf "hasconfig:remote.*.url:git@github.com:**/**"]
path = ~/.gitconfig-github
# 公司内网 GitLab: HTTPS
[includeIf "hasconfig:remote.*.url:https://work-ip-address/**"]
path = ~/.gitconfig-work
# 公司内网 GitLab: SSH
[includeIf "hasconfig:remote.*.url:git@work-ip-address:**/**"]
path = ~/.gitconfig-work
includeIf 的路径支持 ~ 展开,也可以使用绝对路径。条件里的 URL 必须和仓库实际配置的 remote 形式一致,因此 HTTPS 和 SSH 要分别写。
2. GitHub 身份 ~/.gitconfig-github
[user]
name = Example
email = example@users.noreply.github.com
公共仓库可以使用 GitHub 提供的 noreply 邮箱,避免把私人邮箱写入新的 commit 元数据。
3. 公司身份 ~/.gitconfig-work
[user]
name = Work
email = work@company.com
4. 检查当前仓库实际用了哪份配置
先查看远程地址:
git remote -v
再检查姓名和邮箱的来源:
git config --show-origin --get user.name
git config --show-origin --get user.email
在 GitHub 仓库中,输出应指向 ~/.gitconfig-github;在公司仓库中,应指向 ~/.gitconfig-work。
如果当前仓库已经写过本地身份,它的 .git/config 会覆盖全局和 include 文件。确认不再需要本地覆盖后,可以删除:
git config --local --unset-all user.name
git config --local --unset-all user.email
某个键不存在时,--unset-all 会返回非零状态;这不代表 include 配置本身有问题。
这套方式的边界
- 它依赖仓库已经配置了能匹配条件的 remote URL。
- HTTPS 和 SSH 是不同字符串,需要分别匹配。
- include 进来的文件不能再声明 remote URL。
- 它只影响后续 commit 使用的身份,不会修改历史提交。
- 修改历史邮箱属于重写 Git 历史,需要单独评估协作和远端影响。
我现在更愿意用 --show-origin 验证结果,而不是只看 git config user.email 的最终值。前者能直接告诉我身份来自本地仓库、全局文件,还是某个 includeIf 子配置,排错时更省事。