Git 代理配置教学笔记
690 字
3 分钟
Git 代理配置教学笔记
Git 代理配置教学笔记
代理配置只影响 Git 的网络连接,不会修改代码、提交记录或远程仓库内容。
一、什么时候需要配置代理
出现以下情况时,可以检查代理:
- GitHub 无法访问或连接很慢
git fetch、git pull、git push超时- 浏览器可以访问 GitHub,但 Git 命令无法连接
- 更换代理软件或端口后 Git 失效
代理地址和端口应以代理软件显示的信息为准。
二、先检查现有代理
1. 查看 Git 中的代理
git config --show-origin --show-scope --get-regexp '(^http\..*proxy$|^remote\..*\.proxy$)'常见配置层级:
--system 整台电脑--global 当前用户--local 当前项目分别查看:
git config --global --get http.proxygit config --local --get http.proxygit config --local --get remote.origin.proxy没有输出,通常表示该位置未配置代理。
2. 查看环境变量代理
Git Bash 中执行:
printenv | grep -iE '^(http|https|all|no)_proxy='环境变量也可能影响 Git,即使 git config 中没有代理。
三、配置 HTTPS 代理
假设代理软件的 HTTP 代理地址为:
127.0.0.1:7890方案一:只给 GitHub 配置代理(推荐)
git config --global 'http.https://github.com.proxy' 'http://127.0.0.1:7890'方案二:所有 Git HTTPS 请求使用代理
git config --global http.proxy http://127.0.0.1:7890方案三:只配置当前项目
git config --local http.proxy http://127.0.0.1:7890方案四:只配置当前项目的 origin
git config --local remote.origin.proxy http://127.0.0.1:7890SOCKS5 代理示例:
git config --global http.proxy socks5h://127.0.0.1:7890HTTP 端口和 SOCKS5 端口可能不同,不要混用。
四、临时使用或关闭代理
只让当前命令使用代理:
git -c http.proxy=http://127.0.0.1:7890 fetch origin只让当前命令不使用代理:
git -c http.proxy= fetch origin让当前项目的 origin 永久不使用全局代理:
git config --local remote.origin.proxy ""五、删除代理
删除全局代理:
git config --global --unset-all http.proxy删除当前项目代理:
git config --local --unset-all http.proxy删除 origin 的单独代理:
git config --local --unset-all remote.origin.proxy清除当前 Git Bash 会话中的代理变量:
unset HTTP_PROXY HTTPS_PROXY ALL_PROXYunset http_proxy https_proxy all_proxy如果重新打开 Git Bash 后代理再次出现,应检查:
- Windows 环境变量
~/.bashrc~/.bash_profile- 代理软件的终端代理设置
六、测试连接
先确认远程地址:
git remote -v测试是否能访问远程仓库:
git ls-remote origin测试获取远程信息:
git fetch origin查看详细 HTTPS 连接过程:
GIT_TRACE_CURL=1 GIT_TRACE_CURL_NO_DATA=1 git ls-remote origin详细日志可能包含网络信息,不建议完整公开。
七、推荐排查顺序
遇到 Git 网络问题时,按以下顺序检查:
1. 确认代理软件正在运行2. 确认代理协议和端口3. 查看 Git 代理配置4. 查看环境变量代理5. 使用 git ls-remote origin 测试6. 临时关闭代理再次测试不要同时添加多组相互冲突的全局、项目和环境变量代理。
文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!