在使用 Git 时,你可以通过设置代理服务器来访问被限制的资源。Git 支持多种协议(如 HTTP、HTTPS、SSH),不同协议的代理设置方法有所不同。以下是常见的设置方法:

HTTP/HTTPS 协议代理设置

Git 通过 http.proxyhttps.proxy 配置项设置 HTTP/HTTPS 代理。

全局设置(对所有仓库生效)

BASH
# 设置 HTTP 代理
git config --global http.proxy http://代理服务器地址:端口
# 设置 HTTPS 代理
git config --global https.proxy http://代理服务器地址:端口

# 示例
git config --global http.proxy http://127.0.0.1:7890
git config --global https.proxy http://127.0.0.1:7890
点击展开查看更多

单个仓库设置(仅对当前仓库生效)

BASH
# 进入仓库目录后执行
git config http.proxy http://代理服务器地址:端口
git config https.proxy http://代理服务器地址:端口
点击展开查看更多

SSH 协议代理设置

SSH 协议需要修改 SSH 配置文件(通常位于 ~/.ssh/config)。

编辑配置文件

BASH
vim ~/.ssh/config
点击展开查看更多

添加SOCKS5代理

CONFIG
Host github.com  # 针对特定域名设置代理
  HostName github.com
  User git
  ProxyCommand nc -X 5 -x 127.0.0.1:7890 %h %p

Host *  # 对所有域名生效
  ProxyCommand nc -X 5 -x 127.0.0.1:7890 %h %p
点击展开查看更多

参数说明

取消代理设置

BASH
# 取消全局 HTTP/HTTPS 代理
git config --global --unset http.proxy
git config --global --unset https.proxy

# 取消 SSH 代理需编辑 ~/.ssh/config 文件,删除相关配置行
点击展开查看更多

临时使用代理(存疑)

BASH
# 临时为单个命令设置代理
HTTP_PROXY=http://代理服务器地址:端口 HTTPS_PROXY=http://代理服务器地址:端口 git clone https://github.com/username/repo.git
点击展开查看更多

注意事项

  1. 用户名密码认证:如果代理需要认证,格式为:

    BASH
    git config --global http.proxy http://用户名:密码@代理服务器地址:端口
    点击展开查看更多
  2. SOCKS5 代理:若使用 SOCKS5 协议,需确保系统已安装 nc(netcat)或 socat 工具。

版权声明

作者: Chaim

链接: https://chaim.eu.org/posts/%E4%B8%BAgit%E9%85%8D%E7%BD%AE%E4%BB%A3%E7%90%86/

许可证: CC BY-NC-SA 4.0

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Please attribute the source, use non-commercially, and maintain the same license.

开始搜索

输入关键词搜索文章内容

↑↓
ESC
⌘K 快捷键