这里记录一下 Git 配置代理的几种常见方式。
首先要看远程仓库地址是哪种格式:
1
2
| # HTTPS 方式,需要配置 Git 的 HTTP/HTTPS 代理。
https://github.com/user/repo.git
|
1
2
| SSH 方式,需要配置 SSH 的 `ProxyCommand`。
git@github.com:user/repo.git
|
这两个配置代理不是一套配置,排查时要先分清楚。
ps: 查看当前仓库使用的远程地址
对远程地址为 HTTP/HTTPS 仓库设置代理(全局)#
常见 HTTP 代理:
1
2
| git config --global http.proxy 'http://127.0.0.1:1080'
git config --global https.proxy 'http://127.0.0.1:1080'
|
常见 SOCKS5 代理:
1
2
| git config --global http.proxy 'socks5://127.0.0.1:1080'
git config --global https.proxy 'socks5://127.0.0.1:1080'
|
只给当前仓库设置代理#
进入仓库根目录后执行:
1
2
| git config http.proxy 'http://127.0.0.1:1080'
git config https.proxy 'http://127.0.0.1:1080'
|
或者使用 SOCKS5:
1
2
| git config http.proxy 'socks5://127.0.0.1:1080'
git config https.proxy 'socks5://127.0.0.1:1080'
|
这种配置只会写入当前仓库的 .git/config,不会影响其他仓库。
取消代理配置#
取消全局代理:
1
2
| git config --global --unset http.proxy
git config --global --unset https.proxy
|
取消当前仓库代理:
1
2
| git config --unset http.proxy
git config --unset https.proxy
|
如果不确定代理配置到底写在哪里,可以用:
1
| git config --list --show-origin
|
这个命令会把配置来源一起打印出来,方便判断是全局配置,还是当前仓库配置。
只让 GitHub 走代理#
如果不想所有 Git 请求都走代理,只想让 GitHub 走代理,可以在 ~/.gitconfig 里针对域名单独配置。
示例:
1
2
| [http "https://github.com"]
proxy = socks5://127.0.0.1:1080
|
这里不需要再写:
1
2
| [https "https://github.com"]
proxy = socks5://127.0.0.1:1080
|
Git 针对 HTTPS 地址的代理配置,通常仍然放在 [http "..."] 这个 section 下。
完整一点的示例:
1
2
3
4
5
6
7
8
9
| [user]
name = LuoYe
email = xxxx@msn.com
[credential]
helper = manager-core
[http "https://github.com"]
proxy = socks5://127.0.0.1:1080
|
这样配置后,访问 https://github.com 时会走指定代理,但不会影响其他域名。
对远程地址为 SSH 仓库设置代理(全局)#
如果仓库地址是这种:
1
| git@github.com:user/repo.git
|
那么 Git 的 http.proxy / https.proxy 不会生效,因为它走的是 SSH。
SSH 代理需要配置 ~/.ssh/config,配置文件介绍
Linux / macOS 示例:
1
2
3
4
5
| Host github.com
HostName github.com
User git
Port 22
ProxyCommand /usr/bin/ncat --proxy 127.0.0.1:1080 --proxy-type socks5 %h %p
|
Windows 示例:
1
2
3
4
5
| Host github.com
HostName github.com
User git
Port 22
ProxyCommand connect -S 127.0.0.1:1081 %h %p
|
这里要注意几个点:
Host github.com 要和远程地址里的 Host 对上。ProxyCommand 建议使用官方大小写写法。- Windows 下的
connect 不是系统自带命令,如果提示找不到命令,需要额外安装或确认 Git for Windows 是否自带。
如果当前 remote 是:
1
| git@github.com:user/repo.git
|
那么 SSH 配置里的 Host 就应该写:
不要写成其他大小写或别名,除非 remote 里也使用了对应别名。
代理需要认证时的写法#
如果代理服务需要用户名和密码,可以写成:
例如:
1
2
| git config --global http.proxy 'http://user:password@127.0.0.1:7890'
git config --global https.proxy 'http://user:password@127.0.0.1:7890'
|
不过这种方式会把密码明文写入 Git 配置文件,安全性一般。个人环境可以临时使用,长期使用最好换成更安全的认证方式。
Git LFS 注意#
有时普通的 git clone、git pull 正常,但 git lfs pull 失败。
可以用下面的命令检查 Git LFS 当前环境:
如果使用了 Git LFS,排查代理问题时也要看一下 LFS 是否正确继承了 Git 的代理配置。
排查思路#
后面如果 Git 连接 GitHub 失败,可以按这个顺序检查:
- 先看远程地址:
- 再看 Git 配置来源:
1
| git config --list --show-origin
|
- 如果是 HTTPS 地址,检查:
1
2
| git config --get http.proxy
git config --get https.proxy
|
- 如果是 SSH 地址,检查:
- 测试 SSH 连接: