🛠️ Git 如何通过 VPN 代理拉取代码(支持 HTTP / SOCKS5)
在使用 Git 拉取或推送代码时,如果遇到网络不稳定、访问受限或者你正处于公司/学校网络中,挂 VPN 是一种常见的解决方案。但很多人挂上 VPN 后 Git 仍然无法正常使用,这是因为 Git 并不会自动走系统代理,需要手动配置。
本篇将教你如何让 Git 正确通过 VPN(Clash
、V2Ray
、Shadowsocks
等)代理拉取代码。
🌐 1. Git 使用 HTTP 代理
适用场景:
如果你使用的 VPN 工具(如 Clash、Clash Verge、Surfboard)提供 HTTP 代理端口,这是最推荐的方式。
🧾 全局设置代理
git config --global http.proxy http://127.0.0.1:7890
git config --global https.proxy http://127.0.0.1:7890
⚠️ 其中127.0.0.1:7890
是 VPN 提供的 HTTP 代理端口,Clash 默认是7890
,请根据你使用的 VPN 软件调整。
🧽 取消代理
git config --global --unset http.proxy
git config --global --unset https.proxy
🧦 2. Git 使用 SOCKS5 代理(适用于 Shadowsocks / V2Ray)
Git 本身不支持 SOCKS5 协议,但我们可以通过设置环境变量的方式曲线救国。
🧾 临时设置(推荐)
export ALL_PROXY=socks5h://127.0.0.1:1080
git clone https://github.com/xxx/xxx.git
socks5h://
:表示包括 DNS 解析也通过代理(防止 DNS 泄露)。127.0.0.1:1080
:是本地 SOCKS5 代理地址和端口(如 Shadowsocks 的默认端口)。
🧽 取消代理
unset ALL_PROXY
📂 3. 仓库级别设置代理(只对当前仓库生效)
进入你的项目目录后设置:
git config http.proxy http://127.0.0.1:7890
git config https.proxy http://127.0.0.1:7890
取消代理同样在项目目录中操作:
git config --unset http.proxy
git config --unset https.proxy
🧪 示例:Git + Clash 配合使用
Clash 是非常流行的一款代理工具,它默认监听以下端口:
- HTTP 代理:
127.0.0.1:7890
- SOCKS5 代理:
127.0.0.1:7891
你可以执行如下命令,让 Git 使用 HTTP 代理访问:
git config --global http.proxy http://127.0.0.1:7890
git config --global https.proxy http://127.0.0.1:7890
执行 Git 操作:
git pull
# 或
git clone https://github.com/xxx/xxx.git
🧰 附加:一键脚本(可收藏)
✅ 开启代理:
# git-proxy-on.sh
git config --global http.proxy http://127.0.0.1:7890
git config --global https.proxy http://127.0.0.1:7890
❌ 关闭代理:
# git-proxy-off.sh
git config --global --unset http.proxy
git config --global --unset https.proxy
🧩 常见问题 FAQ
Q1:设置了代理,Git 还是失败?
- 检查代理地址是否正确(端口、协议)。
- VPN 代理是否真的启动了?
- 如果你是通过终端代理(如
proxychains
)操作,建议直接用环境变量或 Git 原生配置。
Q2:如何确认代理是否生效?
可以试试访问一个国外的私有仓库,或使用 curl
测试网络连通性。
✅ 小结
场景 | 方式 | 推荐程度 |
---|---|---|
使用 Clash、Surge 提供 HTTP 代理 | git config http.proxy | ⭐⭐⭐⭐ |
使用 Shadowsocks/V2Ray 提供 SOCKS5 | ALL_PROXY=socks5h://... | ⭐⭐⭐ |
单独为某个仓库设置代理 | 仓库目录内配置 | ⭐⭐ |
通过合理配置代理,可以让 Git 顺利拉取或推送代码,再也不用担心“拉取失败”“连接超时”!