Git 设置代理方法(最全)
撰写者 Staff
在国内环境下,访问 GitHub、GitLab 等远程仓库时,经常会遇到连接超时、拉取失败的问题。解决这一问题的最有效方法就是 为 Git 设置代理。
本文将详细介绍:
1. 准备工作:确认代理地址和端口
在设置 Git 代理前,需要确认本地可用的代理地址和端口。常用代理软件(Clash、V2Ray、Shadowsocks 等)默认端口如下:
- HTTP 代理:
http://127.0.0.1:1080 - SOCKS5 代理:
socks5://127.0.0.1:10808
2. Git 全局代理设置
全局代理会影响本机所有使用 HTTP/HTTPS 协议的 Git 仓库。
Important
注意:以下设置的代理仅对 HTTPS 协议 的仓库地址有效(如
https://github.com/...)。如果你使用的是 SSH 协议(如git@github.com:...),请直接跳至 5. SSH 协议代理配置。
# 请替换为实际的IP和端口
git config --global http.proxy http://127.0.0.1:1080
git config --global https.proxy http://127.0.0.1:1080
3. 针对特定域名设置代理
为了避免国内仓库走代理,可只为 GitHub 设置代理:
# 只对 GitHub 设置 SOCKS5 代理
git config --global http.https://github.com.proxy socks5://127.0.0.1:1080
# 只对 GitLab 设置
git config --global http.https://gitlab.com.proxy socks5://127.0.0.1:1080
4. 单个仓库代理设置
进入仓库目录,执行以下命令:
cd /path/to/your-repo
git config http.proxy socks5://127.0.0.1:1080
git config https.proxy socks5://127.0.0.1:1080
临时设置代理(clone 时有效):
git clone -c http.proxy=socks5://127.0.0.1:1080 https://github.com/user/repo.git
5. SSH 协议代理配置
当你使用 SSH 克隆时,Git 并不会读取 git config 中的 http.proxy 配置。你需要配置系统的 SSH 客户端。修改 ~/.ssh/config 文件:
Important
注意:以下设置的代理仅对 SSH 协议 的仓库地址有效(如
git@github.com:...)。如果你使用的是 HTTPS 协议(如https://github.com/...),请直接跳至 2. Git 全局代理设置。
# HTTP 代理
Host github.com
User git
ProxyCommand nc -X connect -x 127.0.0.1:1080 %h %p
# SOCKS5 代理
Host github.com
User git
ProxyCommand nc -X 5 -x 127.0.0.1:1080 %h %p
Tip
Linux / macOS 需要依赖
nc(netcat) 命令,通常系统会自带,若提示报错,请根据您的发行版自行安装。Windows 环境下依赖connect命令,Git bash 中已经包含了connect.exe无需安装。
6. 查看与取消 Git 代理
查看代理
git config --global --get http.proxy
git config --global --get https.proxy
git config --get http.proxy # 当前仓库
取消代理
# 全局取消
git config --global --unset http.proxy
git config --global --unset https.proxy
# 取消特定域名代理
git config --global --unset http.https://github.com.proxy
# 当前仓库取消
git config --unset http.proxy
git config --unset https.proxy
7. 使用环境变量临时设置代理
适用于单次会话:
export http_proxy=socks5://127.0.0.1:1080
export https_proxy=socks5://127.0.0.1:1080
关闭终端后失效。
8. 常见问题与排查
- 无法连接:确认代理软件允许局域网连接;切换
socks5/socks5/http测试。 - 代理需要认证:地址中加入
用户名:密码@。 - SSL 证书问题:可临时禁用(不推荐生产环境):
git config --global http.sslVerify false
- 速度慢:尝试不同端口,或使用 GitHub 镜像。
- Windows 用户:使用 Git Bash 可避免 PowerShell 兼容问题。
9. 总结与最佳实践
- 推荐方法:全局 SOCKS5 设置 +
socks5://。 - 最佳实践:只为 GitHub 等国外仓库设置代理,国内仓库直连。
- SSH 用户:配置
~/.ssh/config以支持代理。
完成设置后,执行 git pull 或 git clone 测试。代理信息保存在 ~/.gitconfig,也可直接编辑该文件。