Skip to content

给 Git 设置代理(HTTP / SSH)的完整教程

给 Git 配好代理,clone / pull / push 全程加速,是开发者最一劳永逸的方案。本文覆盖 HTTP、SOCKS5、只对 GitHub 生效、SSH 走代理、取消代理等所有常见场景。

前提

你本机需要已经运行代理客户端,并知道它的监听地址和端口(常见 http://127.0.0.1:7890 或 SOCKS5 127.0.0.1:1080)。下面命令里的端口请替换成你自己的。

一、全局代理(所有 http/https 请求)

bash
git config --global http.proxy  http://127.0.0.1:7890
git config --global https.proxy http://127.0.0.1:7890

SOCKS5 写法:

bash
git config --global http.proxy  socks5://127.0.0.1:1080
git config --global https.proxy socks5://127.0.0.1:1080

取消:

bash
git config --global --unset http.proxy
git config --global --unset https.proxy

二、只给 GitHub 走代理(推荐)

如果你只想加速 GitHub,不影响访问公司内网 / 国内 Git 服务,用按域名匹配的写法最优雅:

bash
# 只有访问 github.com 时才走代理
git config --global http.https://github.com.proxy http://127.0.0.1:7890

# 取消
git config --global --unset http.https://github.com.proxy

这样 clone 国内 GitLab、Gitee 时不会被代理拖累。

三、SSH 方式走代理

如果你用的是 SSH 地址(git@github.com:user/repo.git),代理要配在 SSH 层,而不是 git config。编辑 ~/.ssh/config(Windows 为 C:\Users\你的用户名\.ssh\config):

通过 HTTP 代理(用 corkscrew / ncat 等):

text
Host github.com
  Hostname github.com
  User git
  # 用 nc 走 SOCKS5 代理(需系统有 nc/ncat)
  ProxyCommand nc -X 5 -x 127.0.0.1:1080 %h %p

Windows 可用 connect.exe(随 Git for Windows 附带):

text
Host github.com
  Hostname github.com
  User git
  ProxyCommand connect -S 127.0.0.1:1080 %h %p

更简单的替代

不想折腾 SSH 代理的话,直接让 SSH 走 443 端口通常就能连上,见 👉 SSH 22 端口失败改用 443

四、查看当前代理配置

bash
git config --global --get http.proxy
# 或列出所有配置
git config --global --list

五、常见问题

Q:配了代理还是慢 / 连不上?

  • 确认代理客户端在跑,端口对不对(HTTP vs SOCKS 端口经常搞混)。
  • curl -x http://127.0.0.1:7890 https://github.com -I 单独测代理是否可用。

Q:push 时报 Failed to connect to 127.0.0.1 port 7890?

  • 说明代理没开或端口错了,而 git 又被配置成走代理。要么开代理,要么 --unset 掉。

Q:公司仓库也被代理了,访问失败?

  • 用方法二(只对 github.com 代理),别用全局代理。

场景速查

你的情况用哪个方法
HTTPS 克隆,只想加速 GitHub方法二
HTTPS 克隆,全部走代理方法一
SSH 克隆方法三 或 SSH 443
想临时关掉--unset 对应项

小结

  • 日常首选 方法二(只对 github.com 代理):既加速又不误伤国内仓库。
  • SSH 用户优先试 443 端口方案,比配 ProxyCommand 简单。
  • 还没有稳定代理?看 代理与工具 栏目。

本文仅供技术学习与研究,请遵守所在国家/地区法律法规。

本站为技术学习交流站点,与 GitHub, Inc. 无任何隶属或官方关系。所有内容仅供技术研究与学习,请遵守所在国家/地区的法律法规。