Git代理配置

1. 协议识别

执行 git remote -v 确认远程仓库协议:

  • http://https://:使用 HTTP 代理配置
  • git@ssh://:使用 SSH 代理配置

2. HTTP/HTTPS 代理配置

Git 统一通过 http.proxy 处理 HTTP 与 HTTPS 流量。

  • 全局生效

    1
    2
    3
    4
    # HTTP/HTTPS 代理
    git config --global http.proxy http://127.0.0.1:<port>
    # SOCKS5 代理
    git config --global http.proxy socks5://127.0.0.1:<port>
  • 指定域名生效(以 GitHub 为例)

    1
    2
    git config --global http.https://github.com.proxy http://127.0.0.1:<port>
    git config --global http.https://github.com.proxy socks5://127.0.0.1:<port>

3. SSH 代理配置

修改 ~/.ssh/config,通过 ProxyCommand 转发流量。

  • Linux / macOS

    1
    2
    3
    Host github.com
    User git
    ProxyCommand nc -X connect -x 127.0.0.1:<port> %h %p
  • Windows

    1
    2
    3
    Host github.com
    User git
    ProxyCommand connect -H 127.0.0.1:<port> %h %p

    注:%h%p 为 SSH 内置占位符,禁止修改。Windows 需确保 connect.exe 已加入 PATH。

4. 验证与清理

1
2
3
4
5
6
7
# 查看当前代理配置
git config --global --get http.proxy
git config --global --get http.https://github.com.proxy

# 清除全局代理
git config --global --unset http.proxy
git config --global --unset http.https://github.com.proxy

5. 配置优先级与注意事项

配置层级 作用范围 优先级
仓库级 (git config) 当前 .git 目录 最高
全局级 (--global) 当前用户所有仓库
系统环境变量 (HTTP_PROXY) 系统全局进程 最低
  • 代理软件需保持运行,否则 Git 操作直接超时。
  • 生产环境建议仅对特定域名配置代理,避免拦截内网或私有仓库流量。
  • SSH 代理配置修改后无需重启,下次连接自动生效。